单链表的遍历链表求解(程序不断生成最后输入的结点)
编译环境:VS2017代码如下:
#include<stdio.h>
#include<malloc.h>
#include<stdbool.h>
typedef struct Node
{
int data;
struct Node *next;
}LNode,*LinkList;
LinkList creat_list()
{
int length, i;
printf("Please the list length:\n");
scanf_s("%d", &length);
LinkList head = (LNode*)malloc(sizeof(LNode));
LinkList p = (LNode*)malloc(sizeof(LNode));
head->next = NULL;
LinkList rear = head;
for (i = 0; i < length; i++)
{
int value;
printf("Please input the value on %d: ", i + 1);
scanf_s("%d", &value);
p->data = value;
p->next = NULL;
rear->next = p;
rear = p;
}
return head;
}
void traverse(LinkList head)
{
LinkList p = head->next;
while (p != NULL)
{
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main()
{
LinkList L = creat_list();
traverse(L);
return 0;
}
错误是比如我输入长度为2,第一个结点是1,第二个结点是2,程序就会不断的输出2并且不停,我看了好长时间也不知道哪里出现了问题,求各位指点一下,十分感谢