Skip to content

Commit a039f9a

Browse files
committed
Create 0143-reorder-list.swift
1 parent 052d492 commit a039f9a

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

swift/0143-reorder-list.swift

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

0 commit comments

Comments
 (0)