对单向链表的综合操作
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<malloc.h> 4 5 #define LEN sizeof(struct student) 6 7 struct student{ 8 long num; 9 float score; 10 struct student *next; 11 }; 12 13 struct student *insert(struct student *head,struct student *stu){ 14 struct student *p0,*p1,*p2; 15 p0=stu; 16 if(head==NULL) 17 { 18 head=p0; 19 p0->next=NULL; 20 } 21 else 22 { 23 p1=head; 24 while(p1->num<p0->num&&p1->next!=NULL) 25 { 26 p2=p1; 27 p1=p1->next; 28 } 29 if(p1->num>p0->num) 30 { 31 if(p1==head) 32 head=p0; 33 else 34 p2->next=p0; 35 p0->next=p1; 36 } 37 else 38 { 39 p1->next=p0; 40 p0->next=NULL; 41 } 42 } 43 return head; 44 } 45 46 struct student *del(struct student *head,long num){ 47 struct student *p1,*p2; 48 if(head==NULL) 49 { 50 printf("The list is NULL.\n"); 51 return head; 52 } 53 p1=head; 54 while(p1->num!=num&&p1->next!=NULL)//当前结点不是要删除的结点而且后面还有结点。 55 { 56 p2=p1; 57 p1=p1->next; 58 } 59 if(p1->num==num) 60 { 61 if(p1==head) 62 head=p1->next; 63 else 64 p2->next=p1->next; 65 } 66 else 67 printf("%ld cannot be found.\n",num); 68 return head; 69 } 70 71 void print(struct student *head) 72 { 73 struct student *p; 74 if(head==NULL) 75 printf("The list is NULL.\n"); 76 else 77 { 78 printf("The data in the list:\n"); 79 for(p=head;p!=NULL;p=p->next) 80 { 81 printf("%ld,%f\n",p->num,p->score); 82 } 83 } 84 } 85 86 struct student *creat(void){ 87 struct student *head=NULL,*p1,*p2; 88 int n=0; 89 90 p1=(struct student *)malloc(LEN); 91 p2=p1; 92 scanf("%ld,%f",&p1->num,&p1->score); 93 while(p1->num!=0) 94 { 95 n++; 96 if(n==1) 97 head=p1; 98 else 99 p2->next=p1; 100 p2=p1; 101 p1=(struct student *)malloc(LEN); 102 scanf("%ld,%f",&p1->num,&p1->score); 103 } 104 p2->next=NULL; 105 return head; 106 } 107 108 int main(){ 109 setbuf(stdout,NULL); 110 struct student *head,*p; 111 long num; 112 printf("Input students' data:\n"); 113 head=creat(); 114 print(head); 115 printf("which one to delete:\n"); 116 scanf("%ld",&num); 117 while(num!=0) 118 { 119 head=del(head,num); 120 print(head); 121 printf("which one to delete:\n"); 122 scanf("%ld",&num); 123 } 124 printf("Insert one new student:\n"); 125 p=(struct student *)malloc(LEN); 126 scanf("%ld,%f",&p->num,&p->score); 127 while(p->num!=0) 128 { 129 head=insert(head,p); 130 print(head); 131 printf("Insert one new student:\n"); 132 p=(struct student *)malloc(LEN); 133 scanf("%ld,%f",&p->num,&p->score); 134 } 135 return 0; 136 }
1.每次插入结点时,必须新开辟一个内存区用于存放新结点的数据。
2.每次循环遍历链表时,要考虑到链表为空的情况(head==NULL)。
3.使用for和while循环遍历链表时的固定套路:(要找到符合某条件的结点)
while:
1 while(p1不满足某条件&&p1->next!=NULL) //p1不满足条件且其后还有结点 2 { 3 p2=p1; //p2记录当前结点 4 p1=p1->next; //p1指向下一个结点 5 } 6 if(p1满足某条件) //跳出循环的两种情况:1.p1满足条件,然后对p1进行处理 7 {} 8 else //2.p1不满足条件且p1是最后一个结点 9 {}
for:
1 for(p=head;p!=NULL;p=p->next) 2 { 3 if(p1不满足条件) 4 p2=p1; 5 else //找到了符合条件的结点p1 6 { 7 …… //对p1处理后,跳出for循环。 8 break; 9 } 10 } 11 if(p1==NULL) //遍历完结点,没有结点满足条件 12 {}