2015-02-05 73 views
0

目前,我正在嘗試編寫鏈表,但遇到問題。 當我執行下面的代碼,它只是打印分配新節點後,根節點的值(空值)沒有改變

當前狀態:

於是我就用GDB,發現當我分配「iHead = newNode」,並返回到主,頭的值沒有改變! 問題是相對於通過價值/參考或任何其他?

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

typedef struct node *nodePtr; 
struct node{ 
    int value; 
    nodePtr next; 
}; 

void print(nodePtr); 
void insert(nodePtr, int); 


int main(void){ 
    nodePtr head = NULL; 

    insert(head, 1); 
    insert(head, 2); 
    insert(head, 3); 
    insert(head, 4); 
    insert(head, 5); 

    print(head); 

    return 0; 
} 

void print(nodePtr iHead){ 
    nodePtr ptr = iHead; 

    printf("Current state:"); 
    while(ptr){ 
     printf("%d ", ptr->value); 
     ptr = ptr->next; 
    } 
    printf("\n"); 
} 

void insert(nodePtr iHead, int iValue){ 
    nodePtr newNode; 

    newNode = (nodePtr) malloc(sizeof(struct node)); 
    newNode->value = iValue; 
    newNode->next = NULL; 

    if(iHead == NULL) 
     iHead = newNode; 
    else{ 
     //find the last node 
     nodePtr ptr = iHead; 
     while(ptr -> next) 
      ptr = ptr->next; 

     //append new node 
     ptr -> next = newNode; 
    } 
} 
+0

歡迎來到Stack Overflow。請儘快閱讀[關於]頁面。您需要將'nodePtr *'傳遞給插入函數,以便它可以覆蓋調用函數中的指針。或者,插入函數需要返回新的根節點:'node ='insert(nodePtr root,int value)''調用像'head = insert(head,3);'。這是一個非常普遍的問題;還有許多其他問題同構於這個問題,答案在於兩種選擇之一。 – 2015-02-05 18:02:01

+0

C是按值撥打的。在函數中更改函數參數不會在調用方中修改它。 – EOF 2015-02-05 18:03:19

回答

1

你正在做價值傳遞。

因此,在函數內完成的更改不會反映在main()中。有兩種方法可以解決這個問題。

  1. void insert(nodePtr *iHead, int iValue)

通行證通過參考本功能

  • nodePtr insert(nodePtr iHead,int iValue)
  • 使在功能的變化,並返回HEAD

    main()有你的清單頭部完好

    nodePtr HEAD = insert(HEAD,2); 
    
    +0

    它的作品!謝謝:) – Simon 2015-02-05 18:37:06