Skip to content

Commit 1339d71

Browse files
authored
Merge pull request #2683 from drxlx/0143-reorder-list
Create 0143-reorder-list.swift
2 parents ee5b5d4 + 0f56739 commit 1339d71

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

swift/0143-reorder-list.swift

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,54 @@
1+
// Slow and Fast Pointer Method
2+
/**
3+
* Question Link: https://leetcode.com/problems/reorder-list/
4+
*/
5+
6+
/**
7+
* Definition for singly-linked list.
8+
* public class ListNode {
9+
* public var val: Int
10+
* public var next: ListNode?
11+
* public init() { self.val = 0; self.next = nil; }
12+
* public init(_ val: Int) { self.val = val; self.next = nil; }
13+
* public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
14+
* }
15+
*/
16+
class ReorderList {
17+
func reorderList(_ head: ListNode?) {
18+
var slow = head
19+
var fast = head?.next
20+
21+
while fast != nil || fast?.next != nil {
22+
slow = slow?.next
23+
fast = fast?.next?.next
24+
}
25+
26+
var second = slow?.next
27+
slow?.next = nil
28+
var prev: ListNode?
29+
30+
while second != nil {
31+
var temp = second?.next
32+
second?.next = prev
33+
prev = second
34+
second = temp
35+
}
36+
37+
var first = head
38+
second = prev
39+
40+
while second != nil {
41+
var temp1 = first?.next
42+
var temp2 = second?.next
43+
first?.next = second
44+
second?.next = temp1
45+
first = temp1
46+
second = temp2
47+
}
48+
}
49+
}
50+
51+
// Deque
152
import DequeModule
253

354
class Solution {
@@ -19,3 +70,4 @@ class Solution {
1970
}
2071
}
2172
}
73+

0 commit comments

Comments
 (0)