我有一個旨在通過一個鏈表來排序號碼清單一個相當基本的程序。傳遞一個指針鏈表在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->旁邊,正在繼續。
對此提出建議?
你打算ADDNODE一個節點添加到的前列表,還是實際將節點添加到排序的位置?意圖不明確。你也應該從功能之外讀出的值,並傳遞它。 – Matt 2012-04-22 22:28:10