单链接列表以for循环的顺序打印

时间:2016-03-08 06:38:47

标签: list loops for-loop

我尝试按照我在链接列表中创建每个节点的顺序打印出链接列表。例如,它应该打印出来" 0 1 2 3 4"但是我的代码错了,并没有打印出任何东西。我认为问题出在我的for循环中。

#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;
    }
}

1 个答案:

答案 0 :(得分:0)

在构建列表时,您似乎被指针算法绊倒了。试试这个:

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;
    }
}