203. 移除链表元素
刷题500,归来仍是外人。
Java链表结构定义
public class ListNode {
int val;
ListNode next;
ListNode(){}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
错误解法
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode dummyHead = new ListNode(0, head);
ListNode cur = dummyHead;
while (cur != null && cur.next != null) {
if (cur.next.val == val) {
cur.next = cur.next.next;
}
cur = cur.next;
}
return dummyHead.next;
}
}
如此做法,示例三不能通过。因为只有下一个节点的值不是val时才能移动到下一个节点,刚刚删除下一个节点时就移动到新的下一个节点就错过了判断新的下一个节点的值的机会。
正确解法
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode dummyHead = new ListNode(0, head);
ListNode cur = dummyHead;
while (cur != null && cur.next != null) {
if (cur.next.val == val) {
cur.next = cur.next.next;
} else {
cur = cur.next;
}
}
return dummyHead.next;
}
}
// 有pre节点
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode dummyHead = new ListNode(0, head);
ListNode cur = head;
ListNode pre = dummyHead;
while (cur != null) {
if (cur.val == val) {
pre.next = cur.next;
} else {
pre = cur;
}
cur = cur.next;
}
return dummyHead.next;
}
}
三种编程语言的空值
- C++
NULL
nullptr
- Java
null
- Python
None