简体   繁体   中英

Single Linked List print in order of for loop

I'm Trying to print out the linked list in the order I created each node in the linked list. For example it should print out "0 1 2 3 4" but my code is wrong and doesn't print out anything. I think the problem lies somewhere in my for loop.

#include <stdio.h>
#include <stdlib.h>
struct node
{
    int data;
    struct node *next;
};

int main(void)
{
    struct node *head = NULL;
    struct node *tail = NULL;
    struct node *current;
    current = head;
    int i;
    for(i = 0; i <= 9; i++)
    {
        current = (struct node*)malloc(sizeof(struct node));
        current-> data = i;
        current-> next = tail;
        tail = current;
        current = current->next;
    }

    current = head;
    while(current)
    {
        printf("i: %d\n", current-> data);
        current = current->next;
    }
}

You appeared to be getting tripped up by the pointer arithmetic when building your list. Try this instead:

int main(void)
{
    struct node *head = NULL;
    struct node *tail = NULL;
    struct node *current;
    int i;
    for (i=0; i <= 9; i++)
    {
        struct node *temp = (struct node*)malloc(sizeof(struct node));
        temp-> data = i;
        temp-> next = NULL;
        if (head == NULL)            // empty list: assign the head
        {
            head = temp;
            tail = temp;
            current = head;
        }
        else                         // non-empty list: add new node
        {
            current-> next = temp;
            tail = temp;
            current = current->next;
        }
    }

    // reset to head of list and print out all data
    current = head;

    while (current)
    {
        printf("i: %d\n", current-> data);
        current = current->next;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM