LeetCode 203 - Remove Linked List Elements - 题解/Solution

https://leetcode.com/problems/remove-linked-list-elements/

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
40
41
42
43
/**
* Remove all elements from a linked list of integers that have value val.
*
* Example
*
* Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
*
* Return: 1 --> 2 --> 3 --> 4 --> 5
*
* @author dongyuxi
*
*/
public class Solution {
public ListNode removeElements(ListNode head, int val) {
if (null == head) {
return head;
}
ListNode newHead = null;
ListNode cur = null;
ListNode temp = head;
while (null != temp) {
while (null != temp && val == temp.val) {
temp = temp.next;
}
if (null == newHead) {
newHead = temp;
cur = newHead;
} else {
if (null != temp) {
cur.next = temp;
cur = cur.next;
}
}
if (null != temp) {
temp = temp.next;
}
}
if (null != cur) {
cur.next = null;
}
return newHead;
}
}


支付宝 微信
文章目录