一个单链表的问题,我感觉是尾插法但是效果是头插法【有代码】

ToddSong 2009-08-21 02:34:09
我每次L的内存地址有变了,但是为什么出来的时候是没变的,问题出在下面的Insert函数里面
#include "stdio.h"
#include "stdlib.h"

typedef struct Lay{
int x;
struct Lay *next;
}Link,*List;

void Init(List *L);
void Insert(List L, int x);
void print(List L);
void main()
{
List p,l;;
int i;
Init(&l);
p=l;
for(i=0;i<10;i++)
{
Insert(p,i);

}
printf("\n");
print(l);

}



void Init(List *L)
{
*L = (List)malloc(sizeof(Link));
(*L)->next=NULL;
}

void Insert(List L,int x) //就是这里有问题
{
List temp;
temp = (List)malloc(sizeof(Link));
temp->x=x;
temp->next=L->next;
L->next=temp;
L=temp; //我每次L的内存地址有变了,但是为什么出来的时候是没变的

}


void print(List L)
{
for(L=L->next;L!=NULL;L=L->next)
printf("%d ",L->x);
printf("\n");
}
...全文
77 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
ToddSong 2009-08-21
  • 打赏
  • 举报
回复
thanks very much!
看来还是对指针这块地址操作理解不透彻啊
galois_godel 2009-08-21
  • 打赏
  • 举报
回复
值传递阿

dio.h"
#include "stdlib.h"
typedef struct Lay{ int x; struct Lay *next; }Link,*List;
void Init(List *L);
void Insert(List *L, int x);
void print(List L);
void main() {
List p,l;;
int i; Init(&l); p=l;
for(i=0;i<10;i++)
{ Insert(&p,i); }
printf("\n");
print(l);
}
void Init(List *L)
{
*L = (List)malloc(sizeof(Link));
(*L)->next=NULL;
}
void Insert(List *pL,int x)
//就是这里有问题
{
List L=*pL;
List temp;
temp = (List)malloc(sizeof(Link));
temp->x=x; temp->next=L->next;
L->next=temp;
*pL=temp; //我每次L的内存地址有变了,但是为什么出来的时候是没变的
}
void print(List L)
{
for(L=L->next;L!=NULL;L=L->next)
printf("%d ",L->x); printf("\n");
}


33,028

社区成员

发帖
与我相关
我的任务
社区描述
数据结构与算法相关内容讨论专区
社区管理员
  • 数据结构与算法社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧