1.建立結構體
1 struct ST 2 { 3 int num;///學號 4 int score;///成績 5 struct ST*next; 6 };///結構體
2.空鏈表的創建
1 struct ST creatNullList(struct ST *head)///創建空鏈表 2 { 3 4 head = (struct ST*)= malloc(sizeof(struct ST)); 5 if(head!=NULL) 6 { 7 head->next=NULL; 8 } 9 else 10 { 11 printf("Out of space!\n"); 12 } 13 return head; 14 };
3.添加結點
1 struct ST append(struct ST *head)///向鏈表中追加結點 2 { 3 struct ST *p,*pnew; 4 pnew=(struct ST*)=malloc(sizeof(struct ST)); 5 /*pnew->n=0; 6 pnew->score=s;//給追加的元素賦值*/ 7 p=head;///p先指向頭結點 8 while(p->next!=NULL) 9 { 10 p=p->next; 11 }///遍歷整個鏈表直到指向鏈尾時退出循環 12 p->next=pnew;///將新結點連入鏈表 13 pnew->next=NULL;///新結點成為鏈尾 14 return head; 15 }
4.刪除結點
1 struct ST Delete(struct ST *head)///刪除鏈表中的結點 2 { 3 int num; 4 struct ST *p,*q; 5 p=head; 6 scanf("%d",&number);///請輸入要刪除的學生的學號 7 while((p->next!=NULL)&&(number!=p->n) 8 { 9 q=p;///q作為中間變量,存儲要刪除的結點之前的一個結點 10 p=p->next;///p存儲的是要刪除的結點 11 } 12 q->next=p-next;///將要刪除的結點排除到鏈表之外 13 return head; 14 }
5.插入結點
1 struct ST Insert(struct ST *head,struct ST *p)///在結點p之后插入一個新的結點 2 { 3 struct ST *pnew; 4 pnew=(struct ST*)=malloc(sizeof(struct ST)); 5 /*pnew->num=n; 6 pnew->score=score;///插入新結點的賦值*/ 7 pnew->next=p->next; 8 p-next=pnew; 9 return head; 10 };