-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0086.Partition List.swift
43 lines (37 loc) · 1.03 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
36
37
38
39
40
41
42
43
/**
* 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? {
var p = head
var arr = [Int]()
while p != nil {
if p!.val < x {
arr.append(p!.val)
}
p = p!.next
}
p = head
while p != nil {
if p!.val >= x {
arr.append(p!.val)
}
p = p!.next
}
var newHead: ListNode? = ListNode()
p = newHead
for i in 0..<arr.count {
let node = ListNode(arr[i])
p!.next = node
p = p!.next
}
return newHead!.next
}
}