导航
导航
文章目录
  1. 题目
  2. 翻译

LeetCode-203.Remove Linked List Elements

题目

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

翻译

移除一个链表中,所有值与val相等的节点。
例如,
给出: 1 –> 2 –> 6 –> 3 –> 4 –> 5 –> 6, val = 6
返回: 1 –> 2 –> 3 –> 4 –> 5

设立两个节点,当前节点为head.next,前驱节点为head。
如果当前节点值与val相等,删除节点,更新当前节点;如果不相等,更新当前节点和前驱节点。
最后判断头结点,如果与值相等,返回head.next,否则直接返回head:

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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeElements(ListNode head, int val) {
if (head == null)
return null;

ListNode last = head, cur = head.next;
while (cur != null) {
if (cur.val == val) {
last.next = cur.next;
cur = cur.next;
} else {
last = cur;
cur = cur.next;
}
}
if (head.val == val)
return head.next;
return head;
}
}

递归解法,参考leetcode讨论区:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeElements(ListNode head, int val) {
if (head == null) return null;
head.next = removeElements(head.next, val);
return head.val == val ? head.next : head;
}
}

参考:
https://leetcode.com/discuss/33043/3-line-recursive-solution