Skip to content

Commit 6128f9e

Browse files
authored
reorder list solution
1 parent d9f2cc3 commit 6128f9e

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

reorder-list/yhkee0404.swift

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
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+
}

0 commit comments

Comments
 (0)