#include <stdio.h>
#include <stdlib.h>
void addNode(int *data);
typedef struct LINKLIST
{
int id;
struct LINKLIST *next;
}L;
L *head=NULL,*tail=NULL;
int main()
{
int n,val;
L *head = (L*)malloc(sizeof(L)),*tail=NULL;
head->next = NULL;
tail = head;
printf("Please input elements'num:\n");
scanf("%d",&n);
for (int i = 0; i < n; i++)
{
printf("number %d is:\n",i+1);
scanf("%d",&val);
addNode(&val);
}
printf("Linklist has been successfully created!\n");
puts("Then output LinkList's data:\n");
head = head->next;
while (head!=NULL)
{
printf("%3d",head->id);
head = head->next;
}
return 0;
}
void addNode(int *data)
{
L *temp = (L*)malloc(sizeof(L));
temp->id = *data;
tail->next = temp;
tail = temp;
temp->next = NULL;
}
以上程序输入数字n->代表有链表n个节点
再通过for循环输入数据并赋值给val,使用addNode(&val);用于增加链表的节点。
但是输出结果未达到预期,能告诉我错在哪里吗?听劝!!
以下是运行结果: