-
Notifications
You must be signed in to change notification settings - Fork 5
/
odd_even_linked_list.go
51 lines (48 loc) · 1.08 KB
/
odd_even_linked_list.go
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
46
47
48
49
50
51
package main
// Definition for singly-linked list.
type ListNode struct {
Val int
Next *ListNode
}
func oddEvenList(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
var evenList *ListNode = &ListNode{Val: -1}
var oddList *ListNode = &ListNode{Val: -1}
var currentEven *ListNode = evenList
var currentOdd *ListNode = oddList
var current *ListNode = head
var i int = 1
for current != nil {
if i%2 != 0 {
currentOdd.Next = current
currentOdd = current
current = current.Next
} else {
currentEven.Next = current
currentEven = current
current = current.Next
}
i++
}
currentOdd.Next = evenList.Next
currentEven.Next = nil
return oddList.Next
}
// func oddEvenList(head *ListNode) *ListNode {
// if head == nil {
// return head
// }
// oddNode := head
// evenNode := head.Next
// even := evenNode
// for evenNode != nil && evenNode.Next != nil {
// oddNode.Next = oddNode.Next.Next
// evenNode.Next = evenNode.Next.Next
// oddNode = oddNode.Next
// evenNode = evenNode.Next
// }
// oddNode.Next = even
// return head
// }