2012-04-22 63 views
1

我有一個旨在通過一個鏈表來排序號碼清單一個相當基本的程序。傳遞一個指針鏈表在C++

當我收到掛了是當元素需要在列表的開頭插入。下面是在代碼問題塊

假設根 - > X = 15,並且假設用戶輸入12提示時:

void addNode(node *root) 
{ 
int check = 0; //To break the loop 
node *current = root; //Starts at the head of the linked list 
node *temp = new node; 


cout << "Enter a value for x" << endl; 
cin >> temp->x; 
cin.ignore(100,'\n'); 


if(temp->x < root->x) 
{ 
    cout << "first" << endl; 
    temp->next=root; 
    root=temp; 

     cout << root->x << " " << root->next->x; //Displays 12 15, the correct response 
} 

但是,如果,在運行此功能後,我嘗試

cout << root->x; 

早在main()中,它再次顯示15。所以代碼

root=temp; 

一旦我離開功能正在丟失。現在,其他對* root的更改,例如將另一個元素添加到LL以及指向root->旁邊,正在繼續。

對此提出建議?

+0

你打算ADDNODE一個節點添加到的前列表,還是實際將節點添加到排序的位置?意圖不明確。你也應該從功能之外讀出的值,並傳遞它。 – Matt 2012-04-22 22:28:10

回答

2

這是因爲你設置本地node *root變量,你是不是修改原始根,但只是在參數堆棧傳遞。

要解決它,你需要使用一個參考指針,例如:

void addNode(node*& root) 

或指向指針:

void addNode(node **root) 
+0

它是不完整的反正。末端大括號在哪裏? – Matt 2012-04-22 22:28:57

+0

Huzzah!我知道這是一些簡單的 @馬特h此不完整的程序,只是在給我找麻煩的一部分。在代碼之後,將元素插入到列表的中間或末尾,這很好。 – 2012-04-22 22:30:40