File tree Expand file tree Collapse file tree 1 file changed +63
-0
lines changed Expand file tree Collapse file tree 1 file changed +63
-0
lines changed Original file line number Diff line number Diff line change 1+ public class ListNode {
2+ public var val : Int
3+ public var next : ListNode ?
4+ public init ( ) { self . val = 0 ; self . next = nil ; }
5+ public init ( _ val: Int ) { self . val = val; self . next = nil ; }
6+ public init ( _ val: Int , _ next: ListNode ? ) { self . val = val; self . next = next; }
7+ }
8+
9+ class Solution {
10+ // Time O(n)
11+ // Space O(1)
12+ func reorderList( _ head: ListNode ? ) {
13+ guard let head = head, head. next != nil , head. next? . next != nil else {
14+ return
15+ }
16+
17+ var slow = head
18+ var fast = head
19+
20+ while fast. next != nil && fast. next? . next != nil {
21+ slow = slow. next!
22+ fast = fast. next!. next!
23+ }
24+
25+ let secondHalf = slow. next
26+ slow. next = nil
27+
28+ let reversedSecondHalf = reverseList ( secondHalf)
29+
30+ mergeLists ( head, reversedSecondHalf)
31+ }
32+
33+ private func reverseList( _ head: ListNode ? ) -> ListNode ? {
34+ var prev : ListNode ? = nil
35+ var current = head
36+
37+ while current != nil {
38+ let nextTemp = current? . next
39+ current? . next = prev
40+ prev = current
41+ current = nextTemp
42+ }
43+
44+ return prev
45+ }
46+
47+ private func mergeLists( _ list1: ListNode ? , _ list2: ListNode ? ) {
48+ var first = list1
49+ var second = list2
50+
51+ while first != nil && second != nil {
52+ let firstNext = first? . next
53+ let secondNext = second? . next
54+
55+ first? . next = second
56+ second? . next = firstNext
57+
58+ first = firstNext
59+ second = secondNext
60+ }
61+ }
62+ }
63+
You can’t perform that action at this time.
0 commit comments