File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * Definition for singly-linked list.
3+ * public class ListNode {
4+ * public var val: Int
5+ * public var next: ListNode?
6+ * public init() { self.val = 0; self.next = nil; }
7+ * public init(_ val: Int) { self.val = val; self.next = nil; }
8+ * public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
9+ * }
10+ */
11+ class Solution {
12+ func reorderList( _ head: ListNode ? ) {
13+ let temp = ListNode ( 0 , head)
14+ solve ( temp, temp, false )
15+ }
16+ func solve( _ tortoise: ListNode , _ hare: ListNode ? , _ odd: Bool ) -> ListNode ? {
17+ guard let safeHare = hare else {
18+ let tail = ListNode ( 0 , tortoise. next)
19+ tortoise. next = nil
20+ return tail
21+ }
22+ let tail = solve ( odd ? tortoise : tortoise. next!, safeHare. next, !odd)
23+ if !odd {
24+ return tail
25+ }
26+ guard let safeTail = tail else {
27+ return nil
28+ }
29+ if safeTail. val == 0 {
30+ return safeTail. next
31+ }
32+ let next = safeTail. next
33+ safeTail. next = tortoise. next
34+ tortoise. next = safeTail
35+ return next
36+ }
37+ }
You can’t perform that action at this time.
0 commit comments