[英]Logic Error Inserting Node in Linked List (Java)
我正在嘗試學習在鏈接列表中插入節點(並返回頭),但是由於某些原因,它是不正確的。
這是我的方法:
1.使用所需數據創建新節點
2.如果要在開頭插入,請將這個新節點指向頭並返回新節點
3.否則,循環到我們要插入節點的位置
-到達目的地后,將要插入的節點指向當前節點的下一個節點
-將當前節點指向要插入的節點
-返回頭
為什么這不起作用? 非常感謝!
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;
}
假設您將新節點插入curr
節點之后,則此循環將一個節點curr
得太遠。
while (currPos < position) {
curr = curr.next;
currPos++;
}
您可以使用筆和紙或使用調試器逐步遍歷代碼,從而輕松解決此問題。
如果將節點插入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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.