我有这段代码,它应该接受一个链表并返回小于参数中指定的节点值的节点,但它做的恰恰相反。我做错了什么?
static LinkedListNode removeNodes(LinkedListNode list, int x) {
LinkedListNode current = list;
while(current.next != null ){
if (current.val >x){
if (current.next.next == null){
break;
}
else{
current = current.next.next;
}
}
else{
current = current.next;
}
}
return current;
}
为了从链表中删除节点,您需要更改 .next 引用而不是当前值。
此外,您的>x应该<</p> x
static LinkedListNode removeNodes(LinkedListNode list, int x) {
LinkedListNode current = list;
while(current.next != null ){
if (current.val < x){
if (current.next.next == null){
break;
}
else{
current.next = current.next.next;
}
}
else{
current = current.next;
}
}
return current;
}