List 按for循环顺序打印单链表

List 按for循环顺序打印单链表,list,loops,for-loop,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; struc

我正在尝试按照我在链表中创建每个节点的顺序打印链表。例如,它应该打印出“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;
    }
}
#包括
#包括
结构节点
{
int数据;
结构节点*下一步;
};
内部主(空)
{
结构节点*head=NULL;
结构节点*tail=NULL;
结构节点*当前;
电流=水头;
int i;
对于(i=0;i数据=i;
当前->下一步=尾部;
尾=电流;
当前=当前->下一步;
}
电流=水头;
while(当前)
{
printf(“i:%d\n”,当前->数据);
当前=当前->下一步;
}
}

在构建列表时,您似乎被指针算法绊倒了。请尝试以下操作:

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;
    }
}
int main(无效)
{
结构节点*head=NULL;
结构节点*tail=NULL;
结构节点*当前;
int i;
对于(i=0;i数据=i;
temp->next=NULL;
if(head==NULL)//空列表:分配head
{
压头=温度;
尾=温度;
电流=水头;
}
else//非空列表:添加新节点
{
当前->下一步=温度;
尾=温度;
当前=当前->下一步;
}
}
//重置为列表标题并打印所有数据
电流=水头;
while(当前)
{
printf(“i:%d\n”,当前->数据);
当前=当前->下一步;
}
}

谢谢!最后我自己完成了这篇文章,现在我了解了指针的基本知识。我的与你的略有不同,我的电流被malloced,然后我的温度被设置为current,但基本前提相同。实际上我试过你的代码,你忘了在else语句末尾将current->next设置为NULL。您需要这样做,因为否则当您在while循环中打印列表时,它将不知道何时停止,并将执行一个奇怪的循环。@DanielMartin实际上,在创建节点时,每个新节点的下一个指针应设置为
NULL