【发布时间】:2021-11-08 05:14:16
【问题描述】:
我正在尝试将值动态存储在链表中。
我希望用户输入链接列表的大小。然后根据我要分配内存的输入(即如果 Input : 3 那么应该创建三个节点)。
如果为节点分配内存,那么我将head 节点存储在temp 中。
之后我想将数据存储在列表中,直到列表结束
我使用的算法如下
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
// Printing the list
void printList(struct node *ptr)
{
int i = 1;
while(ptr != NULL)
{
printf("\n Value in Node %d : %d",i ,ptr->data);
ptr = ptr->next;
i++;
}
}
int main()
{
int n;
struct node *head;
struct node *temp;
printf("\n Enter the size of linkedList : ");
scanf("%d",&n);
head = malloc(sizeof(struct node) * n);
// Storing head in temp
temp = head;
int i = 1; // Keep track on the position of the list
while(temp != NULL) // Untill temp get to end of the list
{
printf("\n Enter the value in node %d : ", i);
scanf("%d",&temp->data);
temp = temp->next; // Assinging next list address
}
printList(head);
return 0;
}
我不明白为什么在执行时它只打印一个值。
我不知道我错了多少?
**输出:**
$ clang dynamicList.c -o a
$ ./a
Enter the size of linkedList : 10
Enter the value in node 1 : 9
Value in Node 1 : 9
【问题讨论】:
标签: c struct linked-list dynamic-memory-allocation singly-linked-list