我正在尝试这个程序,但我无法实现删除。执行进入无限循环。另外,我不确定我是否正确地形成了链表。
我在以下程序中缺少什么:
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:第四