【问题标题】:Single Linked List print in order of for loop单链表按for循环的顺序打印
【发布时间】:2016-06-22 00:04:15
【问题描述】:

我正在尝试按照我在链表中​​创建每个节点的顺序打印出链表。例如它应该打印出“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;
    }
}

【问题讨论】:

    标签: list loops for-loop


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢!我最终自己完成了它,现在了解了指针的基础知识。我的看起来与你的略有不同,因为我的电流被分配,然后我的温度被设置为电流,但基本前提相同。
    • 其实我试过你的代码,你忘了在 else 语句的末尾将 current->next 设置为 NULL。你需要这个,因为否则当你在 while 循环中打印列表时,它不知道什么时候停止并且会做一个奇怪的循环。
    • @DanielMartin 实际上,每个新节点的下一个指针应该在创建节点时设置为NULL
    猜你喜欢
    • 2021-12-03
    • 2021-05-26
    • 1970-01-01
    • 1970-01-01
    • 2018-03-15
    • 1970-01-01
    • 2020-06-01
    • 2022-06-15
    • 1970-01-01
    相关资源
    最近更新 更多