forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RemoveLinkedListElements.swift
39 lines (35 loc) · 1013 Bytes
/
RemoveLinkedListElements.swift
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
/**
* Question Link: https://leetcode.com/problems/remove-linked-list-elements/
* Primary idea: Two pointers, iterate the list and only reserve right nodes
* Time Complexity: O(n), Space Complexity: O(1)
*
* Definition for singly-linked list.
* public class ListNode {
* public var val: Int
* public var next: ListNode?
* public init(_ val: Int) {
* self.val = val
* self.next = nil
* }
* }
*/
class RemoveLinkedListElements {
func removeElements(head: ListNode?, _ val: Int) -> ListNode? {
let dummy = ListNode(0)
dummy.next = head
var prev = dummy
var curr = head
while curr != nil {
if curr!.val == val {
curr = curr!.next
} else {
prev.next = curr
prev = curr!
curr = curr!.next
}
}
// remember to handle the last one
prev.next = nil
return dummy.next
}
}