-
Notifications
You must be signed in to change notification settings - Fork 0
/
0086_partition_list.swift
35 lines (34 loc) · 1.06 KB
/
0086_partition_list.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
// https://leetcode.com/problems/partition-list/
/**
* Definition for singly-linked list.
* public class ListNode {
* public var val: Int
* public var next: ListNode?
* public init() { self.val = 0; self.next = nil; }
* public init(_ val: Int) { self.val = val; self.next = nil; }
* public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
* }
*/
class Solution {
func partition(_ head: ListNode?, _ x: Int) -> ListNode? {
let headForSmallerThanX = ListNode()
var nodeForSmallerThanX = headForSmallerThanX
let headForLargerThanX = ListNode()
var nodeForLargerThanX = headForLargerThanX
var node = head
while node != nil {
let unwrappedNode = node!
node = unwrappedNode.next
unwrappedNode.next = nil
if unwrappedNode.val < x {
nodeForSmallerThanX.next = unwrappedNode
nodeForSmallerThanX = unwrappedNode
} else {
nodeForLargerThanX.next = unwrappedNode
nodeForLargerThanX = unwrappedNode
}
}
nodeForSmallerThanX.next = headForLargerThanX.next
return headForSmallerThanX.next
}
}