我裏面INT主要代碼:將節點添加到鏈表(C++)的末尾?
node *run=NULL, *head=NULL, *temp=NULL;
for (int x = 1; x <= 10; x++)
{
temp = new node();
temp->value = x*10;
temp->next = NULL;
temp -> prev = NULL;
if (head == NULL)
{
head = temp;
}
else
{
run = head;
while (run->next != NULL)
{
run = run->next;
}
temp -> prev = run;
run->next = temp;
}
}
run = head;
cout << "ORIGINAL:" << endl;
while (run != NULL)
{
printf("%d\n", run->value);
run = run->next;
}
cout << endl << endl;
//=============== ADD AT THE END ========================
int xb = 105; //Value I want to add
run = head;
while (run -> next -> value > xb)
{
run = run -> next;
}
temp = new node();
temp -> prev = run;
temp -> value = xb;
temp -> next = NULL;
run -> next = temp;
run = head;
cout << "ADDED 105:" << endl;
while (run != NULL)
{
printf("%d\n", run->value);
run = run->next;
}
我一直在試圖找出這個問題在我的代碼,但沒有增加新的節點(105)我做似乎工作。原來的工作完全正常,輸出
10 20 30 40 50 60 70 80 90 100
但插入的代碼只輸出
10 105
,而不是
10 20 30 40 50 60 70 80 90 100 105
做自己的忙,並且不要分配一個新的節點,直到你的管理指針放在應該插入節點的地方。你在cutline下面設置'temp'是完全錯誤的,你從來沒有正確地連接temp-> next。而且,你的帖子應該包括*期望的*順序結果以及失敗的結果。 *以前的結果雖然有趣,但並不真正相關。 – WhozCraig