2016-03-08 41 views
2

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

回答

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

谢谢!我最终完成了自己,现在了解指针的基础知识。我看起来与你的情况略有不同,因为我目前正在进行调整,然后我的临时工被设置为现在的,但是同样的基本前提。 –

+0

其实我试过你的代码,你忘了在else语句的结尾处设置current-> next。你需要这个,因为否则当你在while循环中打印列表时,它不知道什么时候停止,并且会做一个奇怪的循环。 –

+0

@DanielMartin实际上,在创建节点时,每个新节点的下一个指针应该设置为NULL。 –