#include<stdio.h>//无头节点
#include<stdlib.h>
typedef struct List
{
int val;
struct List *next;
}list;
int main()
{
list *head,*last,*p;
head=(list*)malloc(sizeof(struct List));
head->next=NULL;
int i,n;
scanf("%d",&n);
for(i=0;i<n;i++)
{
p=(list*)malloc(sizeof(struct List));
scanf("%d",&(p->val));
if(i==0)
{
head=p;
last=head;
}
else
{
last->next=p;
last=p;
last->next=NULL;
}
}
while(head)
{
printf("%d ",head->val);
head=head->next;
}
}
为什么当链表长度n为1时输出乱码
已解决
没看到乱码。不过你的 head 节点没输入值。
修改如下,改动处见注释,供参考:
#include<stdio.h>//无头节点
#include<stdlib.h>
typedef struct List
{
int val;
struct List *next;
}list;
int main()
{
list *head,*last,*p;
//head=(list*)malloc(sizeof(struct List)); 这两行多余 修改
//head->next=NULL; 这两行多余
int i,n;
scanf("%d",&n);
for(i=0;i<n;i++)
{
p=(list*)malloc(sizeof(struct List));
scanf("%d",&(p->val));
p->next = NULL; //修改
if(i==0)
{
head=p;
last=head;
}
else
{
last->next=p;
last=p;
//last->next=NULL; //修改
}
}
while(head)
{
printf("%d ",head->val);
head=head->next;
}
return 0;
}