嵌入式-删除链表节点
删除链表节点可以分为三种:删除头节点,删除中间节点和删除尾节点
#include<stdio.h> #include<stdlib.h> struct Test { int data; struct Test * next; }; printfLink(struct Test * head) { while(head!=NULL) { printf("%d\n",head->data); head=head->next; } putchar('\n'); } struct Test * InsertBeforeNode(struct Test *head,int data,struct Test * new) { struct Test * p=head; if(p->data==data) { new->next=head; return new; } while(p->next!=NULL) { if(p->next->data==data) { new->next=p->next; p->next=new; printf("insert OK\n"); return head; } p=p->next; printf("no insert\n"); } return head; } void InsertAfterNode(struct Test *head,int data,struct Test *new) { struct Test * p=head; while(p!=NULL) { if(p->data==data) { new->next=p->next; p->next=new; } p=p->next; } } struct Test * DeleteNode(struct Test *head,int data) { struct Test * p=head; if(p->data==data) { head=head->next; free(p); return head; } while(p->next!=NULL) { if(p->next->data==data) { p->next=p->next->next; return head; } p=p->next; } if(p->next==NULL) { if(p->data==data) { } } return head; } int main() { struct Test *head=(struct Test *)malloc(sizeof(struct Test)); head->data=1; struct Test new1={2,NULL}; struct Test new2={3,NULL}; struct Test new3={4,NULL}; struct Test new4={5,NULL}; printf("no insert:\n"); printfLink(head); InsertAfterNode(head,1,&new1); InsertAfterNode(head,2,&new2); InsertAfterNode(head,3,&new3); printf("after insert 1,2,3:\n"); printfLink(head); struct Test *hp1=InsertBeforeNode(head,2,&new4); printf("after insert 5:\n"); printfLink(hp1); struct Test *hp2=DeleteNode(hp1,1); printf("after delete head Node\n"); printfLink(hp2); printf("after delete Middle Node\n"); struct Test *hp3=DeleteNode(hp2,2); printfLink(hp3); printf("after delete end Node\n"); struct Test *hp4=DeleteNode(hp3,4); printfLink(hp4); return 0; }
输出结果:
no insert:
1
after insert 1,2,3:
1
2
3
4
insert OK
after insert 5:
1
5
2
3
4
after delete head Node
5
2
3
4
after delete Middle Node
5
3
4
after delete end Node
5
3
4556