forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RemoveDuplicatesFromSortedListII.swift
58 lines (52 loc) · 1.52 KB
/
RemoveDuplicatesFromSortedListII.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/**
* Question Link: https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/
* Primary idea: Three pointers, iterate the list and only reserve right nodes,
* specially handle the last one afterwards
*
* Note: Swift provides "===" to compare two objects refer to the same reference
*
* 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 RemoveDuplicatesfromSortedListII {
func deleteDuplicates(head: ListNode?) -> ListNode? {
if head == nil || head!.next == nil {
return head
}
let dummy = ListNode(0)
dummy.next = head
var node = dummy
var prev = head
var post = head!.next
while post != nil {
if post!.val != prev!.val && prev!.next === post{
node.next = prev
node = prev!
prev = post!
post = post!.next
} else {
if post!.val != prev!.val {
prev = post!
post = post!.next
} else {
post = post!.next
}
}
}
if prev!.next != nil {
node.next = nil
} else {
node.next = prev
}
return dummy.next
}
}