-
Notifications
You must be signed in to change notification settings - Fork 0
/
odd_even_linked_list_medium.go
88 lines (76 loc) · 1.69 KB
/
odd_even_linked_list_medium.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// Odd Even Linked List
// https://leetcode.com/explore/interview/card/top-interview-questions-medium/107/linked-list/784/
// medium
// Simple linked list management
package main
import (
"log"
"strconv"
)
func main() {
head := list("12345")
l3 := oddEvenList(head)
printList(l3)
}
func list(str string) *ListNode {
startNode := ListNode{}
node := &startNode
for i:=len(str)-1; i>=0; i-- {
node.Val, _ = strconv.Atoi(string(str[i]))
nodeNew := ListNode{}
if i>0 {
node.Next = &nodeNew
}
node = &nodeNew
}
return &startNode
}
func printList(node *ListNode) {
log.Println("list=")
log.Println(node)
acc := ""
for node != nil {
str := strconv.Itoa(node.Val)
acc = acc + str
node = node.Next
}
log.Println(acc)
}
type ListNode struct {
Val int
Next *ListNode
}
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func oddEvenList(head *ListNode) *ListNode {
if head == nil {
return head
}
var lastOdd, cursor *ListNode
lastOdd = head
currentEven := true
cursor = head
for cursor != nil && cursor.Next != nil {
if !currentEven {
// save link to the right element at insert
firstEven := lastOdd.Next
// save link to the right element at cursor
next := cursor.Next.Next
// insert
lastOdd.Next = cursor.Next
lastOdd.Next.Next = firstEven
// manage cursorS
lastOdd = lastOdd.Next
cursor.Next = next
} else {
cursor = cursor.Next
}
currentEven = !currentEven
}
return head
}