2011-03-26 33 views
1

所以我使用通過引用在我的鏈表上的代碼,但問題是它不是印刷洙我怎麼才能真正解決這個問題?使用通過鏈接列表的引用傳遞

我的代碼:

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

struct node 
{ 
     int x; 
     struct node *next; 
}; 

void add(struct node **root, int x) 
{ 
     struct node *conductor; 
     if(root==NULL) 
     { 
      (*root)=malloc(sizeof(struct node)); 
      (*root)->x=x; 
      (*root)->next=NULL ;   
     } 
     else 
     { 
      conductor = *root; 
      while(conductor->next!=NULL) 
      { 
       conductor = conductor -> next;    
      } 
      conductor->next=malloc(sizeof(struct node)); 
      conductor->next->x=x; 
      conductor->next->next=NULL; 
     } 
}  

void display(struct node *root) 
{ 
     struct node *conductor; 
     conductor=root; 
     while(conductor!=NULL) 
     { 
      printf("%d",conductor->x); 
      conductor = conductor ->next;       
     } 
} 



int main() 
{ 
    struct node *root; 
    root=NULL; 
    add(&root,5); 
    add(&root,4); 
    display(root); 
    free(root); 
    system("pause"); 
} 

在更好的形式 http://codepad.org/CPdUvK0x

是不是在我的程序的所有節點都聯繫?

+1

請接受您的上一個問題的答案http://stackoverflow.com/questions/5433967/how-to-remove-any-node-in-a-singly-linked-請點擊旁邊的複選標記。 – 2011-03-26 12:59:58

+0

「通過引用傳遞」在C中不存在。但有值傳遞的值是指針。 – BenjaminB 2011-03-26 13:24:06

回答

3
void add(struct node **root, int x) 
{ 
     struct node *conductor; 
     if(root==NULL) 

如果(*root == NULL)

既然你打電話add(&root...root永遠不會爲這應該是。

+0

謝謝:)這是我的愚蠢回答,我沒有看到我笑我的屁股,當我看到這個答案愚蠢的我xDD – 2011-03-26 13:15:38

1

的檢查:

if(root==NULL) 

應該

if(*root==NULL) 

root正在被轉交地址。

同時你做了free(root)來釋放整個不正確的列表,因爲它只釋放第一個節點,導致其他節點不可訪問導致內存泄漏。爲了解決這個問題,你需要通過一個作爲釋放的節點之一:

struct node *tmp = root; 
while(root) { 
    tmp = root->next; 
    free(root); 
    root = tmp; 
} 
0

問題在add()

if(root==NULL) 

這個測試是錯誤的:根引用傳遞永遠不能爲null(在main中看到,它包含根節點的地址)。你應該正確測試,如果rrot節點爲NULL:

if (*root == NULL) 

我還想補充一點,你釋放分配給IST內存的方式是錯誤的:

free(root) 

只會釋放根節點,但會泄漏子節點...