今天学习了链表的插入,有很多的易错点,导致我在练习的时候一直运行不对,记录一下,谨防再次出错
先上代码
1 #include<stdio.h> 2 #include<stdlib.h> 3 typedef struct NODE 4 { 5 int id; 6 char *name; 7 char *tel; 8 struct NODE *next; 9 }Node; 10 Node *GetNode(int id,char *name,char *tel); 11 void AddNode(Node **ppHead,Node **ppEnd,Node *pNode); 12 void InsertNode(Node **ppHead,Node **ppEnd,Node *pNode,int id); 13 14 int main() 15 { 16 Node *pHead = NULL; 17 Node *pEnd = NULL; 18 19 AddNode(&pHead,&pEnd,GetNode(1,"qwe","123654789")); 20 AddNode(&pHead,&pEnd,GetNode(2,"ert","123654789")); 21 AddNode(&pHead,&pEnd,GetNode(3,"rty","123654789")); 22 AddNode(&pHead,&pEnd,GetNode(4,"sdf","123654789")); 23 InsertNode(&pHead,&pEnd,GetNode(8,"pdf","123456789"),32); 24 while(pHead != NULL) 25 { 26 printf("%d %s %s\n",pHead->id,pHead->name,pHead->tel); 27 pHead = pHead->next; 28 } 29 30 return 0; 31 } 32 33 Node *GetNode(int id,char *name,char *tel) 34 { 35 Node *pTemp = (Node *)malloc(sizeof(Node)); 36 pTemp ->id = id; 37 pTemp ->name = name; 38 pTemp ->tel = tel; 39 pTemp ->next = NULL; 40 41 return pTemp; 42 } 43 44 void AddNode(Node **ppHead,Node **ppEnd,Node *pNode) 45 { 46 if(*ppHead == NULL) 47 { 48 *ppHead = pNode; 49 } 50 else 51 { 52 (*ppEnd)->next = pNode; 53 } 54 *ppEnd = pNode; 55 56 return; 57 } 58 59 void InsertNode(Node **ppHead,Node **ppEnd,Node *pNode,int id) 60 { 61 Node *pMove = *ppHead; 62 if((*ppHead)->id == id) //1 63 { 64 pNode->next = (*ppHead); 65 (*ppHead) = pNode; 66 return; 67 } 68 while((pMove->next) != NULL) //2 69 { 70 if((pMove->next->id) == id) 71 { 72 pNode->next = pMove->next; 73 pMove->next =pNode; 74 return; //3 75 76 } 77 pMove = pMove->next; 78 } 79 (*ppEnd)->next = pNode; 80 *ppEnd = pNode; 81 82 return; 83 84 85 }
链表插入的思路(此处默认为插入在给定id的结点前):
- 插入在头结点前,即给的id此处为1;
- 插在中间;
- 插在末尾,即给的id不在我已经创建的结点之内;
我当时犯的错误:
- 在注释2处 ,写为1 while(pMove != NULL) ,就忽略了若是遍历到最后一个结点时,p->next == NULL ,那么p->next->id就不存在,则下一行的if就会崩溃,造成整个程序崩溃
- 在注释3处,并未加入 return 跳出,就会一直加入我设置的新结点,并且新结点一直指向p->next 从而跳出不循环,程序运行后没有结果
总结:
在编写代码时,要先画清逻辑分析图,针对于链表而言 在添加和插入的时候,一定要先连后断,先连接新结点,再断老结点的指针例如
pNode->next = *ppHead;
*ppHead = pNode;
pNode->next = pMove->next;
pMove->next = pNode;
2019-04-19 22:54:44 编程小菜鸟反思,大佬勿喷,谢谢!