2014-02-25 76 views
0

main函数中,我用n = 50和next = NULL构成一个节点。当我将add添加到链表时,尽管它已被添加,但它在遍历时不会显示。发生这种情况的原因是因为当调用add函数时,指向具有50的节点的start指针未更新为指向具有10的新节点。 (第28行到第34行)。在c中链接列表遍历

#include <stdio.h>  
#include <stdlib.h> 

typedef struct node 
{ 
    int n; 
    struct node* next; 
} node; 

void traverse(node* start) 
{ 
    while(true) 
    { 
     printf("%i\n",start->n); 
     start = start->next; 
     if(start == NULL) 
     { 
      break; 
     } 
    } 
} 

void add(int num, node* start) 
{ 
    node* previous = NULL; 
    node* current = start; 
    if(num<current->n) 
    { 
//------------------------------------------------------------------------------ 

     //The problem is inside this if block. 
     node* tmp = malloc(sizeof(node)); 
     tmp->next = current; 
     current = tmp; 
//------------------------------------------------------------------------------- 

    } 
    else 
    { 
     while(true) 
     { 
      previous = current; 
      current = current->next; 
      if(current == NULL) 
      { 
       node *tmp = malloc(sizeof(node)); 
       tmp->n = num; 
       tmp->next = NULL; 
       previous->next = tmp; 
       break; 
      } 
      else 
      { 
       if(current->n > num) 
       { 
        node *tmp = malloc(sizeof(node)); 
        tmp->n = num; 
        tmp->next = current; 
        previous->next = tmp; 
        break; 
       } 
      } 
     } 
    } 
} 
int main(void) 
{ 
    node* start = malloc(sizeof(node)); 
    start->n = 50; 
    start->next = NULL; 
    add(10,start); 
    traverse(start); 
} 

我该如何解决这个问题?

+2

你的函数应该能够正确地管理一个* empty *列表(即空头指针)。在'main()'中加载一个导入哨兵noad'start'的拐杖最好是脆弱的,结果函数依赖于它(例如:如果传递NULL指针,'traverse'将调用UB)。而你的'add()'比它需要的时间长大约85%。 – WhozCraig

+0

@WhozCraig在add()中我需要'current'和'previous'吗?我怎样才能缩短'add()'? –

+1

没有。你可以用一个临时指针和一个指向指针(你将作为参数传递)来做到这一点。 [**现场直播**](http://ideone.com/OwzYFk) – WhozCraig

回答

3

您需要将指针作为指针传递给add函数中的指针,以便您可以在指定的位置准确地修改它。宣言应该看起来像void add(int num, node** start)

此外,您应该注意在程序结束前释放分配给列表的内存。