移除链表元素
题目链接:203. 移除链表元素 - 力扣(LeetCode)
代码随想录:代码随想录 (programmercarl.com)
思路:首先要了解链表的结构,本题有两种解法,是够设置虚拟额头节点,建议设置虚拟的头节点,这样代码会更加简洁而统一,要注意代码的不同
设置虚拟头节点的代码:
class Solution {
public ListNode removeElements(ListNode head, int val) {
if(head==null){
return head;
}
ListNode dummy=new ListNode(-1,head);
ListNode pre=dummy;
ListNode cur=head;
while(cur!=null){
if(cur.val==val){
pre.next=cur.next;
}else{
pre=cur;
}
cur=cur.next;
}
return dummy.next;
}
}
没有设置虚拟头节点,需要对头节点进行额外的控制:
public ListNode removeElements(ListNode head, int val) {
while (head != null && head.val == val) {
head = head.next;
}
// 已经为null,提前退出
if (head == null) {
return head;
}
// 已确定当前head.val != val
ListNode pre = head;
ListNode cur = head.next;
while (cur != null) {
if (cur.val == val) {
pre.next = cur.next;
} else {
pre = cur;
}
cur = cur.next;
}
return head;
}