链表插入
根据给定插入条件,可以分为多种插入函数;
- 给定插入位置pos 初始有0 1 两种情况
- 给定插入元素key 初始有前插和后插两种情况
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#define N 100
#define OVERFLOW 0
#define OK 1
// list insert
typedef struct student
{
int num;
struct student *next;
}stu,*slist;
struct Node *creat(int n)
{
int i;
struct student *head, *p1, *p1_last;
int a;
head = NULL;
printf("input the integers:\n");
for(i=0; i<n; i++)
{
p1 = (slist)malloc(sizeof(stu)); //storage allocation
scanf("%d",&a);
p1->num = a;
if(head == NULL)
{
head = p1;
p1_last = p1;
}
else
{
p1_last->next = p1;
p1_last = p1;
}
}
p1_last->next = NULL;
return head;
};
struct student *list_insert_posfst1(struct student* p, int val, int i)
{
struct student *q = (slist)malloc(sizeof(stu));
struct student *h = p;
q->num = val;
if(i == 1) //every output is the case of i = 1; so i need to check whether if is constant right ;
{
q->next = p;
return q;
}
else
{
i-=2;
while(i--)
{
p = p->next; //find insert front pointer;
if(p == NULL)
exit(1);
}
q->next = p->next; //insert code
p->next = q;
return h;
}
};
struct student *list_insert_posfst0(struct student* p, int val, int i)
{
struct student *q = (slist)malloc(sizeof(stu));
struct student *h = p;
q->num = val;
if(i == 0) //every output is the case of i = 1; so i need to check whether if is constant right ;
{
q->next = p;
return q;
}
else
{
i--;
while(i--)
{
p = p->next; //find insert front pointer;
if(p == NULL)
exit(1);
}
q->next = p->next; //insert code
p->next = q;
return h;
}
};
struct student *list_insert_afterkey(struct student* p, int val, int key)
{
slist h = p;
slist q = (slist)malloc(sizeof(stu));
q->num = val;
while(p->num != key)
{
if(p == NULL) exit(1);
p = p->next;
}
q->next = p->next;
p->next = q;
return h;
};
struct student *list_insert_beforekey(struct student* p, int val, int key)
{
slist h = p;
slist q = (slist)malloc(sizeof(stu));
q->num = val;
while(p->next->num != key)
{
if(p == NULL) exit(1);
p = p->next;
}
q->next = p->next;
p->next = q;
return h;
};
int main()
{
int temp,i,n;
struct student*p, *head;
printf("input the count of the list:\n");
scanf("%d", &n);
p = creat(n);
head = list_insert_posfst0(p,521,3);
printf("the position from 0 insert 521 :");
while(head != NULL)
{
printf("%d ", head->num);
head = head->next;
}
printf("\n\n");
head = list_insert_posfst1(p,777,3);
printf("the position from 1 insert 777 :");
while(head != NULL)
{
printf("%d ", head->num);
head = head->next;
}
printf("\n\n");
head = list_insert_beforekey(p,999,3);
printf("before 3 insert 999 :");
while(head != NULL)
{
printf("%d ", head->num);
head = head->next;
}
printf("\n\n");
head = list_insert_afterkey(p,888,3);
printf("after 3 insert 888 :");
while(head != NULL)
{
printf("%d ", head->num);
head = head->next;
}
printf("\n\n");
return 0;
}