简体   繁体   English

单个链接列表按for循环顺序打印

[英]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. 例如,它应该打印出“ 0 1 2 3 4”,但是我的代码是错误的,什么也没打印出来。 I think the problem lies somewhere in my for loop. 我认为问题出在我的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;
    }
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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