C程序来遍历一个单独链接的lisk



我编写了一个C程序来实现遍历单链表的概念。程序首先通过请求用户输入来创建列表,然后显示/遍历创建的列表。当我运行这段代码时,它成功地创建了链表,但在显示创建的列表时,它会产生一个无限循环。`

#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node *next;
} *head;
int main(){
struct node *newNode, *temp;
int n;
printf("Enter number of Nodes: ");
scanf("%d",&n);
if(n <= 1){
printf("Invalid Input Nodes should Nodes should be greater than 1");
exit(0);

}
else{
head = (struct node *)malloc(sizeof(struct node));
if(head == NULL){
printf("No Memory Allocation");
exit(0);
}
else{
printf("Node Data 1: ");
scanf("%d",&head -> data);
head -> next = NULL;
temp = head;
}
newNode = (struct node *)malloc(sizeof(struct node));
if(newNode == NULL){
printf("No Memory Allocation");
exit(0);
}
else{
for(int i = 2; i <= n; ++i){
printf("Node Data %d: ",i);
scanf("%d",&newNode -> data);
newNode -> next = NULL; 
temp -> next = newNode;  
temp = temp -> next;

}
}

//Traversal        
struct node *ptr;     
ptr = head;   
if(ptr == NULL)  
{  
printf("Empty list..");  
}  
else  
{   
while (ptr != NULL){  
printf("n%d",ptr->data);  
ptr = ptr -> next;  
}  
}  
}
return 0;
}

`

在这个for循环中

for(int i = 2; i <= n; ++i){
printf("Node Data %d: ",i);
scanf("%d",&newNode -> data);
newNode -> next = NULL;
temp -> next = newNode;

}

将相同的指针newNode分配给数据成员temp->下一个相当于表达式head->下一个原因是在循环中指针温度没有改变。

您需要在循环中分配新节点,并重新分配指针临时。

此外,您还需要检查变量n的输入值。例如,如果n设置为1,则将存在内存泄漏。

如果变量n的输入值不等于INT_MAX,则不存在无限循环。

程序可以按照以下方式

#include <stdio.h>
#include <stdlib.h>
int main( void )
{
struct node 
{
int data;
struct node *next;
} *head = NULL;
unsigned int n = 0;
printf( "Enter number of Nodes: " );
scanf( "%u", &n );
if (n != 0)
{
head = malloc( sizeof( struct node ) );
if (!head)
{
puts( "No Memory Allocation" );
exit( 0 );
}
else 
{
printf( "Node Data 1: " );
scanf( "%d", &head->data );
head->next = NULL;

unsigned int i = 0;
for (struct node *temp = head;  ++i < n; temp = temp->next)
{
if (( temp->next = malloc( sizeof( struct node ) ) ) == NULL)
{
puts( "No Memory Allocation" );
break;
}
temp->next->next = NULL;
printf( "Node Data %u: ", i + 1 );
scanf( "%d", &temp->next->data );
}
for (const struct node *current = head; current != NULL; current = current->next)
{
printf( "%d -> ", current->data );
}
puts( "null" );
}
}
}

程序输出为

Enter number of Nodes: 5
Node Data 1: 1
Node Data 2: 2
Node Data 3: 3
Node Data 4: 4
Node Data 5: 5
1 -> 2 -> 3 -> 4 -> 5 -> null

请注意,您需要在程序中添加将释放所有分配内存的代码。

相关内容

  • 没有找到相关文章

最新更新