#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node* next;
}Lnode,*List;
List Init(List L)
{
L=(List)malloc(sizeof(Lnode));
if(L==NULL)
{
printf("结点生成失败!");
}
L->next=NULL;
return L;
}
List createList(int len)//尾插法
{
int i;
int e;
List L=Init(L);
List r,n;
r=L;//尾指针初始化为头指针
for(i=0;i<len;i++)
{
scanf("%d",&e);
n=(List)malloc(sizeof(List));//申请空间
if(n==NULL)
return NULL;
n->data=e;
n->next=NULL;//新指针指针域置空
r->next=n;//将新指针链入单链表末尾
r=r->next;//尾指针往后移
}
return L;
}
/*List createList(int len)//头插法
{
int i;
List L=Init(L);
List p;
for(i=0;i<len;i++)
{
p=(List)malloc(sizeof(List));
scanf("%d",&p->data);
p->next=L->next;//将新结点接入头结点后
L->next=p;
}
return L;
}*/
void printLinkList(List L,int len)
{
int i;
if(!L)
printf("没有元素");
for(i=0;i<len;i++)
{
L=L->next;
printf("%d ",L->data);
}
}
int main()
{
Lnode* L=NULL;
int len;
scanf("%d",&len);
L=createList(len);
printf("当前链表所有元素");
printLinkList(L,len);
return 0;
}
代码中,有两个地方出现了问题:
List createList(int len)
中,您在申请节点空间时,使用了sizeof(List)
,这会导致分配的空间大小不正确。List
是指向struct node
的指针类型,应该使用sizeof(struct node)
。修改前:
n=(List)malloc(sizeof(List));
修改后:
n=(List)malloc(sizeof(struct node));
void printLinkList(List L,int len)
中,当打印链表元素时,您在循环中使用了L = L->next
,这将导致链表的头节点被跳过,从而导致打印结果错误。应该在循环之前将L
指向链表的第一个节点。修改前:
for(i=0;i<len;i++)
{
L = L->next;
printf("%d ",L->data);
}
修改后:
L = L->next; // 将L指向链表的第一个节点
for(i=0;i<len;i++)
{
printf("%d ",L->data);
L = L->next;
}
通过这些修改,应该能够编译通过并正常运行。
将你的代码保存为 list1.c,运行成功了。你遇到什么错?
根据可以直接编译通过的,应该跟你的编译器有关系~
供参考,改动处见注释:
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node* next;
}Lnode, * List;
List Init(List L)
{
L = (List)malloc(sizeof(Lnode));
if (L == NULL)
{
printf("结点生成失败!");
}
L->next = NULL;
return L;
}
List createList(int len)//尾插法
{
int i;
int e;
List L = Init(L);
List r, n;
r = L;//尾指针初始化为头指针
for (i = 0; i < len; i++)
{
scanf("%d", &e);
n = (List)malloc(sizeof(Lnode));// 修改 sizeof(List)是结构体指针的大小
//n = (List)malloc(sizeof(List));//申请空间
if (n == NULL)
return NULL;
n->data = e;
n->next = NULL;//新指针指针域置空
r->next = n;//将新指针链入单链表末尾
r = r->next;//尾指针往后移
}
return L;
}
/*List createList(int len)//头插法
{
int i;
List L=Init(L);
List p;
for(i=0;i<len;i++)
{
p=(List)malloc(sizeof(Lnode)); // 修改
//p=(List)malloc(sizeof(List));
scanf("%d",&p->data);
p->next=L->next;//将新结点接入头结点后
L->next=p;
}
return L;
}*/
void printLinkList(List L, int len)
{
int i;
if (!L)
printf("没有元素");
for (i = 0; L->next && i < len; i++) //for (i = 0; i < len; i++) 修改
{
L = L->next;
printf("%d ", L->data);
}
}
int main()
{
Lnode* L = NULL;
int len;
scanf("%d", &len);
L = createList(len);
printf("当前链表所有元素");
printLinkList(L, len);
return 0;
}