gpt4 book ai didi

java - 删除链表中的第k个元素(Java实现)

转载 作者:行者123 更新时间:2023-11-30 06:22:10 24 4
gpt4 key购买 nike

我正在尝试这个程序,但我无法实现删除。执行进入无限循环。另外,我不确定我是否正确地形成了链表。

我在以下程序中缺少什么:

public class SpecificNodeRemoval {
private static class Node {
String item;
Node next;
Node prev;

private Node(String item, Node next, Node prev) {
this.item = item;
this.next = next;
this.prev = prev;
}
}

public static void main(String[] args) {
int k = 3;

Node fourth = new Node("Fourth", null, null);
Node third = new Node("Third", fourth, null);
Node second = new Node("Second", third, null);
Node first = new Node("First", second, null);

second.prev = first;
third.prev = second;
fourth.prev = third;
Node list = first;

Node result = removalKthNode(list, k);

int j = 1;
while(result.next!=null){
System.out.println(j+": "+result.item);
}
}

private static Node removalKthNode(Node first, int k) {
Node temp = first;

for(int i=1; i < k; i++) {
temp = temp.next;
}

temp.prev.next = temp.next;
temp.next.prev = temp.prev;

return temp;
}
}

非常感谢您的回答和评论。工作程序如下所示:

public class SpecificNodeRemoval {
private static class Node {
String item;
Node next;
Node prev;

private Node(String item, Node next, Node prev) {
this.item = item;
this.next = next;
this.prev = prev;
}
}

public static void main(String[] args) {
int k = 3;

Node fourth = new Node("Fourth", null, null);
Node third = new Node("Third", fourth, null);
Node second = new Node("Second", third, null);
Node first = new Node("First", second, null);

second.prev = first;
third.prev = second;
fourth.prev = third;
Node list = first;

Node result = removalKthNode(list, k);

int j = 1;
while(result != null){
System.out.println(j+": "+result.item);
result = result.next;
j++;
}
}

private static Node removalKthNode(Node first, int k) {
Node temp = first;

for(int i=1; i < k; i++) {
temp = temp.next;
}

temp.prev.next = temp.next;
temp.next.prev = temp.prev;

return first;
}
}

输出是: 1:首先 2:第二 3:第四个

最佳答案

这看起来像是罪魁祸首。

while(result.next!=null){
System.out.println(j+": "+result.item);
}

你没有在链表中前进。

我不太确定你的意图,但你可能想写如下以避免无限循环......

while(result !=null){
System.out.println(j+": "+result.item);
result = result.next;
j++;
}

但是如果你想打印整个链表,你不应该用从 removalKthNode 函数返回的值初始化 result。您应该从首先开始。

希望这是有道理的。

关于java - 删除链表中的第k个元素(Java实现),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19699774/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com