java未能删除LinkedList中的第一个节点,但成功删除了其他节点
我正在练习使用Java的LinkedList
这里的主要方法是删除给定索引的节点
除了第一个节点外,可以正确删除给定节点
如果我将removeLastKthNode(head, lastKth);
更改为head = removeLastKthNode(head, lastKth)
,它会工作
但是我不知道为什么removeLastKthNode(head, lastKth)
不能删除第一个节点
安德烈亚斯给了我一个关于这个问题的链接 Is Java "pass-by-reference" or "pass-by-value"?
然而,这里的问题是,当“lastKth”不引用第一个节点(头节点)时,“removeLastKthNode”表现为“按引用传递”
可以肯定的是,“removeLastKthNode”的行为方式类似于“通过引用传递”。 但是当“lastKth=arr.length”时,为什么方法“removeLastKthNode”的行为不像“通过引用传递”
这里令人困惑
以下是一些结果:
当“lastKth=6”
Initial LinkedList:
2 4 6 8 11 3 7
After remove last6th LinkedList:
2 6 8 11 3 7
当“lastKth=7”
Initial LinkedList:
2 4 6 8 11 3 7
After remove last7th LinkedList:
2 4 6 8 11 3 7
谢谢塞基的建议。我自己编写了代码,并添加到下面的代码中
节点定义:
public class Node {
public int value;
public Node next;
public Node(int data) {
this.value = data;
}
}
主要代码:
import java.util.*;
public class RemoveLastKthNode_single {
public static void main(String[] args) {
int[] arr = {2, 4, 6, 8, 11, 3, 7};
//Arrays.sort(arr);
Node head = arrayToNode(arr);
System.out.println("Initial LinkedList:");
displayNode(head);
System.out.println();
int lastKth = 7;
removeLastKthNode(head, lastKth);
System.out.println("After remove last" + lastKth + "th" + " LinkedList:");
displayNode(head);
}
// refer https://www.jianshu.com/p/0d0dbfcbc1c3
public static Node arrayToNode(int[] arr) {
Node head = new Node(arr[0]);
Node other = head;
for (int i = 1; i < arr.length; i++) {
Node temp = new Node(arr[i]);
other.next = temp;
other = other.next;
}
return head;
}
public static void displayNode(Node head) {
while(head != null) {
System.out.print(head.value + " ");
head = head.next;
}
System.out.println();
}
public static Node removeLastKthNode(Node head, int lastKth) {
if (head == null || lastKth < 1) {
return head;
}
Node cur = head;
while (cur != null) {
lastKth --;
cur = cur.next;
}
if (lastKth == 0) {
head = head.next;
}
if (lastKth < 0) {
cur = head;
while (++lastKth != 0) {
cur = cur.next;
}
cur.next = cur.next.next;
}
System.out.println(head.value + " YES ");
return head;
}
}
感谢安德烈亚斯的评论。我知道它是怎么工作的
这是我的逻辑。对“head节点”的引用通过值传递给“removeLastKthNode”,因此在内存中我有一个head的副本。“头”的副本也指向“下一个节点”。它看起来像一条“双头蛇”。我可以切割“身体”(因为它们是完全一样的),但我不能切割一条蛇的“头”,并让另一条蛇的“头”也被切割。因为他们在记忆中是不同的
图片在这里
<p style="text-align:center;"> <img src="https://i.stack.imgur.com/3dfHw.png" width="280" height="150"> </p>
共 (0) 个答案