2014-10-30 56 views
-1

這是給我麻煩的部分。在我的圖中,我指着頭,然後把我的新頭設定爲P,但它在現實生活中並沒有成功。有什麼建議麼?鏈接列表推前不能正常工作

{ 
         // p points to a new node 
    Node *p = new Node(s,0); 

if(head == 0)   // head not pointing to a node yet? 
{ 
    head = tail = p; // head & tail point to new node in the list 
} 
else 
{      // head->next points to new node 
    head  = p-> get_next(); 
    head = p; 


      // head points to first node in the list 
} 

這裏是get_next()函數。

Node *Node::get_next() const // get a Node * (value of next) 
{ 
return next;    //returns current objects pointer to next 
} 

我試圖在以前的一些情況我心中已經看到網上看,我開始懷疑我的get_next()是錯誤的。不幸的是我必須用它來完成這項任務。

+2

只要你將它設置爲p-> next – 2014-10-30 02:51:05

+1

在其他部分中,你就會用p覆蓋頭部//就像這樣評論// head-> next指向新節點,但是分配p-> next頭,而不是頭 - >下一頁= p – 2014-10-30 02:55:21

+0

[MCVE](http://stackoverflow.com/help/mcve)請!是的,我是一個代碼納粹,如果有人對此有所懷疑! – 2014-10-30 02:55:56

回答

0

您也需要分配給P->下一個直接(如利津C「的答案),或使用一個set_next(節點*)功能。 get_next()只返回p-> next的的值(即一個Node對象的地址),它不允許你修改它,這就是你要做的。

一個set_next功能會是這個樣子:然後

// Returned pointer is just for convenience, this could easily be void 
Node* Node::set_next(Node* newNext) 
{ 
    return p->next = newNext; 
} 

你else塊變爲:

else 
{ 
    // p->next points to head 
    p.set_next(head); 
    head = p; 
    // head points to first node in the list 
} 

編輯:還有一兩件事。您的代碼當前編寫的方式(即作爲一個單向鏈表,只能在一個方向上遍歷),您不需要尾指針。即使你計劃pop_back(),你仍然需要遍歷整個列表來找到新的tailhead是你所需要的。

+0

它的工作,但我有點困惑。爲什麼把頭放在()使它工作?謝謝,btw – user3743209 2014-10-30 03:16:23

+0

@ user3743209'head'是一個Node * - 一個Node對象在內存中的位置 - 就像'p'和'p-> next'一樣,對吧?將'head'傳遞給函數允許'p'將'head'的值賦給它的'next'成員。 – Wlerin 2014-10-30 03:23:19

2

它應該是

p-> next = head;

head = p;

即讓新創建的節點的下一個頭部和改變頭新創建的節點