Java 无法从链表类中删除第一个节点
我有个问题。我正在使用破解编程面试课本练习一些关于链表的面试问题,在解决问题之前,我尝试实现我自己的LinkedList数据结构。我试图测试这个类的功能。其他一切都很好,但我不知道如何删除LinkedList的第一个节点 在发现我自己的代码实现不起作用后,我尝试了CTCI手册中的代码,但没有成功。下面是我的链表数据结构代码:Java 无法从链表类中删除第一个节点,java,linked-list,singly-linked-list,Java,Linked List,Singly Linked List,我有个问题。我正在使用破解编程面试课本练习一些关于链表的面试问题,在解决问题之前,我尝试实现我自己的LinkedList数据结构。我试图测试这个类的功能。其他一切都很好,但我不知道如何删除LinkedList的第一个节点 在发现我自己的代码实现不起作用后,我尝试了CTCI手册中的代码,但没有成功。下面是我的链表数据结构代码: static class Node{ Node next = null; int data; public Node(in
static class Node{
Node next = null;
int data;
public Node(int d) {
data = d;
}
void appendToTail(int d) {
Node end = new Node(d);
Node n = this;
while(n.next != null) {
n = n.next;
}
n.next = end;
}
Node deleteNode(Node head, int d) {
if(head == null) return null;
Node n = head;
if(n.data == d) {
return head.next;
}
while(n.next != null) {
if(n.next.data == d) {
n.next = n.next.next;
return head;
}
n = n.next;
}
return head;
}
int size () {
int length = 0;
Node n = this;
if(n == null) {
return 0;
}
length = 1;
while(n.next != null) {
n = n.next;
length++;
}
return length;
}
void printNode() {
Node d = this;
while(d != null) {
if(d.next != null) {
System.out.print(d.data + " --> ");
} else {
System.out.println(d.data + " ");
}
d = d.next;
}
}
}
我想知道为什么我能够删除除第一个节点之外的所有其他节点
我确实设置了以下测试用例:
public static void main(String[] args) {
//test cases
Node test = new Node(0);
for(int i = 1; i <= 20; i++) {
test.appendToTail(i);
}
test.printNode();
for(int i = 0; i <= 20; i = i + 2) {
test.deleteNode(test, i);
}
test.printNode();
}
publicstaticvoidmain(字符串[]args){
//测试用例
节点测试=新节点(0);
对于(int i=1;i 3-->5-->7-->9-->11-->13-->15-->17-->19
,但我的预期输出是1-->3-->5-->7-->9-->11-->13-->15-->17-->19
问题是,删除链表中的第一个元素时,您正在发送头。下一步,但您没有在测试变量中使用它
代码应该是
public static void main(String[] args) {
//test cases
Node test = new Node(0);
for(int i = 1; i <= 20; i++) {
test.appendToTail(i);
}
test.printNode();
for(int i = 0; i <= 20; i = i + 2) {
test = test.deleteNode(test, i);
}
test.printNode();
}
那么结果就是
0 --> 1 --> 2 --> 3 --> 4 --> 5 --> 6 --> 7 --> 8 --> 9 --> 10 --> 11 --> 12 --> 13 --> 14 --> 15 --> 16 --> 17 --> 18 --> 19 --> 20
3 --> 5 --> 7 --> 9 --> 11 --> 13 --> 15 --> 17 --> 19
您需要
deleteNode()
返回列表的第一个节点。如果删除除第一个节点以外的任何节点,都不会有任何更改。但是,如果删除第一个节点,它将返回第二个节点。解决方案是有效的,尽管我不确定它是否会将代码的复杂性增加到不切实际的程度,因为您必须在linkedlist中迭代n^2次(n对于删除的每个元素,从技术上讲,n(n+1)/2仍然是O(n^2))。
0 --> 1 --> 2 --> 3 --> 4 --> 5 --> 6 --> 7 --> 8 --> 9 --> 10 --> 11 --> 12 --> 13 --> 14 --> 15 --> 16 --> 17 --> 18 --> 19 --> 20
3 --> 5 --> 7 --> 9 --> 11 --> 13 --> 15 --> 17 --> 19