2016-10-17 82 views
1

我試圖學習在鏈表中插入一個節點(並返回頭部),但由於某種原因它不正確。邏輯錯誤在鏈接列表(Java)中插入節點

這是我的方法:

1.創建所需的數據

2.新節點。如果我們想將它插入開始的時候,這點新節點的頭並返回新節點

否則,環路的地方,我們要插入節點的位置

-一旦到了那兒,指向節點要插入的下一個當前節點的下一個

-點當前節點到節點插入

-返回頭

爲什麼這不起作用?非常感謝!

Node InsertNth(Node head, int data, int position) { 
    Node node = new Node(); 
    node.data = data; 

    if (position == 0) { 
     node.next = head; 
     return node; 
    } 
    else { 
     Node curr = head; 
     int currPos = 0; 

     while (currPos < position) { 
      curr = curr.next; 
      currPos++; 
     } 
     node.next = curr.next; 
     curr.next = node; 
    } 
    return head; 
} 
+2

你是什麼意思不起作用?到底發生了什麼?請解釋你的問題;不要讓我們讀代碼來搞清楚。 – ChiefTwoPencils

+0

在高層次代碼看起來不錯,請讓我們知道您面臨的問題。 –

+0

此外,電話是什麼樣的;它是'head = insert(...);'? – ChiefTwoPencils

回答

-1

如果將節點插入到Head中,則需要將Head設置爲要插入的節點。

Node InsertNth(Node head, int data, int position) { 
Node node = new Node(); 
node.data = data; 

if (position == 0) { 
    node.next = head; 
    head = node; 
} 
else { 
    Node curr = head; 
    int currPos = 0; 

    while (currPos < position) { 
     curr = curr.next; 
     currPos++; 
    } 
    node.next = curr.next; 
    curr.next = node; 
} 
return head; 

}

+0

按照共享的算法,頭將被返回。這已經在if循環中完成了。 –

+0

如果你插入節點作爲頭部,它會在方法結尾返回頭部,指向插入的節點,因爲在if循環中我們做'head = node;' – djointster

+0

如果循環內部有返回聲明。它不會結束該方法。 if(position == 0){node_next = head; 返回節點; } –

0

既然你的curr節點之後插入新的節點,該環路太遠步驟一個節點。

while (currPos < position) { 
    curr = curr.next; 
    currPos++; 
} 

您可以輕鬆地通過使用筆和紙或調試程序逐步完成代碼。