首页 > 解决方案 > 为什么我的代码的遍历部分不起作用?

问题描述

链表创建成功,但从节点检索数据,即;没有给出预期的输出。遍历部分不会遍历所有数据元素,而是无限次仅给出一个数据元素的输出。当我运行程序时,它需要所有数据元素,但遍历部分即;(显示整个列表)没有给出预期的输出

  `/**
 * 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

标签: data-structuressingly-linked-list

解决方案


我认为你应该在 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;  
}
}
}

推荐阅读