链表从指定前方插入节点
在链表的前方插入节点
#include<stdio.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; } } int main() { struct Test head={1,NULL}; struct Test new1={2,NULL}; struct Test new2={3,NULL}; struct Test new3={4,NULL}; InsertAfterNode(&head,1,&new1); printf("after insert:\n"); printfLink(&head); struct Test *hp=InsertBeforeNode(&head,2,&new3); printf("after insert:\n"); printfLink(hp); return 0; }
首先通过InsertAfterNode在data=1的节点的后面插入一个new1节点,然后通过InsertBeforeNode在data=2的节点前插入一个new3节点
输出结果:
after insert:
1
2
insert OK
after insert:
1
4
2
添加调试的手段:
gcc InsertLinkNode.c -g
gdb a.out
就可以看到是哪里报错
4556