Skip to content

Commit 0e850d9

Browse files
author
Yi Gu
committed
[LinkedList] Add a solution to Odd Even Linked List
1 parent ed8f03e commit 0e850d9

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

LinkedList/OddEvenLinkedList.swift

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/odd-even-linked-list/
3+
* Primary idea: Prev-post two pointers; change the prev and move both at a time
4+
* Time Complexity: O(n), Space Complexity: O(1)
5+
*
6+
* Definition for singly-linked list.
7+
* public class ListNode {
8+
* public var val: Int
9+
* public var next: ListNode?
10+
* public init(_ val: Int) {
11+
* self.val = val
12+
* self.next = nil
13+
* }
14+
* }
15+
*/
16+
17+
class OddEvenLinkedList {
18+
func oddEvenList(_ head: ListNode?) -> ListNode? {
19+
guard head != nil && head!.next != nil else {
20+
return head
21+
}
22+
23+
let evenHead = head!.next
24+
var p = head
25+
var q = evenHead
26+
var isEndEven = true
27+
28+
while q!.next != nil {
29+
let node = q!.next
30+
31+
p!.next = node
32+
33+
p = q
34+
q = node
35+
isEndEven = !isEndEven
36+
}
37+
38+
if isEndEven {
39+
p!.next = evenHead
40+
} else {
41+
p!.next = nil
42+
q!.next = evenHead
43+
}
44+
45+
return head
46+
}
47+
}

0 commit comments

Comments
 (0)