2013-12-09 88 views
0

我應該創建一個函數來顯示第一個節點中的數據,然後使該節點成爲列表中的最後一個節點。但我認爲更簡單的方法是將第一個節點作爲列表的頭部,並在包含前一個第一個節點的數據的列表的末尾插入一個新節點,然後嘗試使用不同的方法,但是這樣做時我得到了隨機問號和符號,我嘗試了不同的方法,但我無法真正弄清楚問題所在。在列表末尾插入一個節點與第一個節點的數據

代碼附加以下

int places::showfirst() 
    { 
     node * current = head; 
     node * temp = current -> next; 
     node * temp2 = new node; 
     cout << "The first place you visited is \n\n\t\n " << current -> place << endl; 
     current->place = temporary; 
     first = new char [strlen(temporary) +1]; 
     strcpy(first,temporary); 

     while(current->next) 
     { 
       current = current -> next; 
     } 
     head = temp; 
     current -> next = temp2; 
     temp2 -> next = NULL; 
     temp2->place = first; 

     cout<<"THIS IS THE NEW LAST NODE " << temp2->place << endl; 
     return 1; 
    } 

任何建議,將不勝感激,謝謝你在前進。

+0

不是創建一個新的節點,爲什麼不接着設置的最後一個節點到要移動到結束節點的? – fjc

回答

1

無需重新分配內存或取消分配IMO。你可以簡單地改變鏈接並轉換現有的頭節點到最後一個:

node * current = head; 
node * temp = current -> next; 
cout << "The first place you visited is \n\n\t\n " << current -> place << endl; 
while(current->next) 
{ 
    current = current -> next; 
} 
current -> next = head; 
head -> next = NULL; 
head = temp; 
+0

在「current - > next = head」之後添加一個temp2並將其分配給該方法後,非常感謝! – azizj

相關問題