java无法从链表类中删除第一个节点
我有个问题。我正在使用破解编程面试课本练习一些关于链表的面试问题,在解决问题之前,我尝试实现我自己的LinkedList数据结构。我试图测试这个类的功能。其他一切都很好,但我不知道如何删除LinkedList的第一个节点
在发现我自己的代码实现不起作用后,我尝试了CTCI手册中的代码,但没有成功。下面是我的链表数据结构代码:
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();
}
删除所有偶数节点后收到的输出是0 --> 1 --> 3 --> 5 --> 7 --> 9 --> 11 --> 13 --> 15 --> 17 --> 19
,但预期的输出是1 --> 3 --> 5 --> 7 --> 9 --> 11 --> 13 --> 15 --> 17 --> 19
# 1 楼答案
问题是,当删除链表中的第一个元素时,您正在发送头。下一步,但您不会在测试变量中使用它
代码应该是
加上这个
那么结果就是