-
Notifications
You must be signed in to change notification settings - Fork 21
/
RemoveDuplicatesFromSortedListII.swift
61 lines (50 loc) 路 1.71 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
59
60
61
//
// RemoveDuplicatesFromSortedListII.swift
// LeetCode
//
// Created by 榛庤档澶儙 on 27/11/2017.
// Copyright 漏 2017 lizhaotailang. All rights reserved.
//
// Given a sorted linked list, delete all nodes that have duplicate numbers,
// leaving only distinct numbers from the original list.
// For example,
// Given 1->2->3->3->4->4->5, return 1->2->5.
// Given 1->1->1->2->3, return 2->3.
//
// Accepted. See [RemoveDuplicatesFromSortedListII](./LeetCodeTests/RemoveDuplicatesFromSortedListIITests.swift) for test cases.
//
import Foundation
class RemoveDuplicatesFromSortedListII {
func deleteDuplicates(_ head: ListNode?) -> ListNode? {
if head == nil {
return nil
}
let fakeHead = ListNode(0)
fakeHead.next = head
var node: ListNode? = fakeHead
while node?.next != nil {
var tmp = node?.next
if tmp?.next != nil && tmp?.val == tmp?.next?.val {
while tmp?.next != nil && tmp?.val == tmp?.next?.val {
tmp = tmp?.next
}
node?.next = tmp?.next
tmp?.next = nil
} else {
node = node?.next
}
}
return fakeHead.next
}
public class ListNode: Equatable {
public var val: Int
public var next: ListNode?
public init(_ val: Int) {
self.val = val
self.next = nil
}
public static func ==(lhs: RemoveDuplicatesFromSortedListII.ListNode, rhs: RemoveDuplicatesFromSortedListII.ListNode) -> Bool {
return lhs.val == rhs.val && lhs.next == rhs.next
}
}
}