data-structures - 为什么我的代码的遍历部分不起作用?
问题描述
链表创建成功,但从节点检索数据,即;没有给出预期的输出。遍历部分不会遍历所有数据元素,而是无限次仅给出一个数据元素的输出。当我运行程序时,它需要所有数据元素,但遍历部分即;(显示整个列表)没有给出预期的输出
`/**
* C program to create and traverse a Linked List
*/
#include <stdio.h>
#include <stdlib.h>
/* Structure of a node */
struct node {
int data; // Data
struct node *next; // Address
}*head;
/*
* Functions to create and display list
*/
void createList(int n);
void traverseList();
int main()
{
int n;
printf("Enter the total number of nodes: ");
scanf("%d", &n);
createList(n);
printf("\nData in the list \n");
traverseList();
return 0;
}
/*
* Create a list of n nodes
*/
void createList(int n)
{
struct node *newNode, *temp;
int data, i;
head = (struct node *)malloc(sizeof(struct node));
// Terminate if memory not allocated
if(head == NULL)
{
printf("Unable to allocate memory.");
exit(0);
}
// Input data of node from the user
printf("Enter the data of node 1: ");
scanf("%d", &data);
head->data = data; // Link data field with data
head->next = NULL; // Link address field to NULL
// Create n - 1 nodes and add to list
temp = head;
for(i=2; i<=n; i++)
{
newNode = (struct node *)malloc(sizeof(struct node));
/* If memory is not allocated for newNode */
if(newNode == NULL)
{
printf("Unable to allocate memory.");
break;
}
printf("Enter the data of node %d: ", i);
scanf("%d", &data);
newNode->data = data; // Link data field of newNode
newNode->next = NULL; // Make sure new node points to NULL
temp->next = newNode; // Link previous node with newNode
temp = temp->next; // Make current node as previous node
}
}
/*
* Display entire list
*/
void traverseList()
{
struct node *temp;
// Return if list is empty
if(head == NULL)
{
printf("List is empty.");
return;
}
temp = head;
while(temp != NULL)
{
printf("Data = %d\n", temp->data); // Print data of current node
temp = temp->next; // Move to next node
}
} `
the expected output should be
Enter the total number of nodes: 5
Enter the data of node 1: 10
Enter the data of node 2: 20
Enter the data of node 3: 30
Enter the data of node 4: 40
Enter the data of node 5: 50
Data in the list
Data = 10
Data = 20
Data = 30
Data = 40
Data = 50
解决方案
我认为你应该在 if 之后使用 else 条件
在 else 条件中包含 while(temp!=null) 和之后的代码并检查
void display()
{
struct node *ptr;
ptr=head;
if(head==NULL)
printf("null");
else
{
while(ptr!=NULL)
{
printf("%d->",ptr->data);
ptr=ptr->next;
}
}
}
推荐阅读
- reactjs - Laravel 7 + React 渲染错误:渲染没有返回任何内容
- javascript - 通过每个元素之间的嵌套值过滤对象数组
- python - 如何在Python中的IF条件中使用isin函数
- rust - 使用 Pest.rs,如何在关键字后允许非重要空格?
- regex - 正则表达式匹配单词中的a字符串,并且该单词必须出现在句子的最后一个单词
- java - 在评估流口水时的条件时,无法访问同一议程组中修改后的事实
- clang-tidy - clang-tidy 配置中没有等效的`-line-filter`?
- typescript - Cypress - Typescript - 我怎样才能使我的夹具变量全局化?
- cassandra - 将 Cadence 连接到 Azure Cosmo Cassandra API
- r - 如何在r中绘制两个正镜像条形图?