为什么我的代码的遍历部分不起作用?

时间:2019-06-19 17:08:12

标签: data-structures singly-linked-list

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

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

1 个答案:

答案 0 :(得分:0)

我认为您应该在if之后使用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;  
}
}
}