forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PartitionList.swift
45 lines (39 loc) · 1.1 KB
/
PartitionList.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
/**
* Question Link: https://leetcode.com/problems/partition-list/
* Primary idea: Tail Insert and merge two lists
*
* Note: Swift provides "!==" to determine 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 PartitionList {
func partition(head: ListNode?, _ x: Int) -> ListNode? {
let prevDummy = ListNode(0)
var prev = prevDummy
let postDummy = ListNode(0)
var post = postDummy
var node = head
while node != nil {
if node!.val < x {
prev.next = node
prev = node!
} else {
post.next = node
post = node!
}
node = node!.next
}
post.next = nil
prev.next = postDummy.next
return prevDummy.next
}
}