为了账号安全,请及时绑定邮箱和手机立即绑定

链表插入函数问题,关于指针指向

链表插入函数问题,关于指针指向

呼如林 2019-02-25 08:13:32
原链表1 2 3。第一段函数运行正确,插入后为1 2 4 3;改为第二段代码运行,结果为2 3 4。问题来了,注意我标出的地方p=(*L);第一段函数我用p做链表元素操作,第二段全替换为(*L)链表元素操作。为什么结果却不同了,如果p是(*L)的指针,结果应该相同;如果(*L)只是给p赋值的话,那么showlist()函数应该显示(*L)原链表而不是修改过的p链表?我想问题主要是我对p=(*L);的理解不够吧 status Listinsert(Linklist *L,int j,Elemtype e) { Linklist p,r; p=(*L); // int i=2; r=(Linklist)malloc(sizeof(Node)); r->data=e; r->next=NULL; while(i<j) { i++; p=p->next; } r->next=p->next; p->next=r; return OK; } 和 status Listinsert(Linklist *L,int j,Elemtype e) { Linklist p,r; //p=(*L); //下面用(*L)替换p,运行后有问题 int i=2; r=(Linklist)malloc(sizeof(Node)); r->data=e; r->next=NULL; while(i<j) { i++; (*L)=(*L)->next; //替换 } r->next=(*L)->next; //替换 (*L)->next=r; return OK; } //////////////////////////////////////// 完整代码 #include <stdio.h> #include <stdlib.h> typedef int status,Elemtype; #define OK 1 #define NO 0 typedef struct Node { status data; struct Node *next; } Node; typedef struct Node* Linklist; void Initlist(Linklist *L) { (*L)=(Linklist)malloc(sizeof(struct Node)); (*L)->data=0; (*L)->next=NULL; } status Listinsert(Linklist *L,int j,Elemtype e) ////正确 { Linklist p,r; p=*L; int i=2; r=(Linklist)malloc(sizeof(Node)); r->data=e; r->next=NULL; while((*L)&&i<j) { i++; p=p->next; } r->next=p->next; p->next=r; return OK; } status Getelem(Linklist L,int j,Elemtype *e) { Linklist p; int i;// for(i=0; i<j-1; i++) { p=L->next; L=p; } L->next=NULL; (*e)=L->data; return OK; } void showlist(Linklist L) { Linklist p; while(L) { printf("%d\n",L->data); p=L->next; L=p; } } int main() { int x=1; int *e=&x; Node *root,first,second,third; first.data=1; first.next=&second; second.data=2; second.next=&third; third.data=3; third.next=NULL; root=&first; //showlist(root); // if(Getelem(root,3,e)) // printf("%d",*e); if(Listinsert(&root,3,4)==1) showlist(root); return 0; }
查看完整描述

1 回答

  • 1 回答
  • 0 关注
  • 513 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号