-
Notifications
You must be signed in to change notification settings - Fork 886
/
OddEvenLinkedList.swift
45 lines (37 loc) · 1.09 KB
/
OddEvenLinkedList.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
* Question Link: https://leetcode.com/problems/odd-even-linked-list/
* Primary idea: Prev-post two pointers; change the prev and move both at a time
* Time Complexity: O(n), Space Complexity: O(1)
*
* Definition for singly-linked list.
* public class ListNode {
* public var val: Int
* public var next: ListNode?
* public init(_ val: Int) {
* self.val = val
* self.next = nil
* }
* }
*/
class OddEvenLinkedList {
func oddEvenList(_ head: ListNode?) -> ListNode? {
guard head != nil, head!.next != nil else {
return head
}
var prev = head, post = head!.next, isEndEven = true
let evenStart = post
while post!.next != nil {
prev!.next = post!.next
prev = post
post = post!.next
isEndEven = !isEndEven
}
if isEndEven {
prev!.next = evenStart
} else {
prev!.next = nil
post!.next = evenStart
}
return head
}
}