203. Remove Linked List Elements

问题
Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.

设置哨兵节点,将其next指向头部。
设置前节点,将其指向哨兵节点。
设置尾部节点,并指向头部。
移动当前节点尾部,如尾部的val等于需要删去的val,则将前节点的next指向尾部的next。
尾部的next如为null,则前节点的next指向null。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
* Definition for singly-linked list.
* 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) {
if (head == null){
return head;
}
ListNode dummyHead = new ListNode();
dummyHead.next = head;

ListNode preNode = dummyHead;
ListNode tail = dummyHead.next;

while( tail != null ){
if ( tail.next == null && tail.val == val ){
preNode.next = null;
break;
}
else if (tail.val == val){
preNode.next = tail.next;
tail = preNode.next;
}
else{
preNode = preNode.next;
tail = tail.next;
}
}

return dummyHead.next;
}
}
Author

Xander

Posted on

2022-04-09

Updated on

2022-04-08

Licensed under

Comments