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
Solution1:Iterative 遍历 依次比较删除
思路:创建dummy,遍历依次比较删除
实现1_a:没有考虑deleted结点的回收
实现1_b: 考虑deleted结点的回收
Time Complexity: O(N) Space Complexity: O(1)
Solution2:递归(前序) 比较删除
先处理当前level
Time Complexity: O(N) Space Complexity: O(N) 递归缓存
Solution2:递归(后序) 比较删除
后处理当前level
Time Complexity: O(N) Space Complexity: O(N) 递归缓存
Solution1a Code:
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode cur = head, prev = dummy;
while (cur != null) {
if (cur.val == val) {
prev.next = cur.next;
} else {
prev = prev.next;
}
cur = cur.next;
}
return dummy.next;
}
}
Solution1b Code:
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode cur = head, prev = dummy;
while (cur != null) {
ListNode next = cur.next;
if (cur.val == val) {
cur.next = null;
prev.next = next;
//prev.next = cur.next;
} else {
prev = prev.next;
}
cur = next;
}
return dummy.next;
}
}
Solution2a Code:
class Solution {
public ListNode removeElements(ListNode head, int val) {
if (head == null) return null;
if (head.val == val) {
head = removeElements(head.next, val);
} else {
head.next = removeElements(head.next, val);
}
return head;
}
}
Solution2b Code:
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;
}