mirror of
https://github.com/cubixle/codekata-golang.git
synced 2026-04-24 23:04:42 +01:00
code kata 230826
This commit is contained in:
76
code_kata_230826/reorder_list_test.go
Normal file
76
code_kata_230826/reorder_list_test.go
Normal file
@@ -0,0 +1,76 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func reorderList(head *node) {
|
||||
if head == nil || head.next == nil || head.next.next == nil {
|
||||
return
|
||||
}
|
||||
|
||||
f, s := head, head
|
||||
for f.next != nil && f.next.next != nil {
|
||||
f = f.next.next
|
||||
s = s.next
|
||||
}
|
||||
|
||||
sh := s.next
|
||||
printList(sh)
|
||||
s.next = nil
|
||||
printList(head)
|
||||
var pre *node
|
||||
for sh != nil {
|
||||
next := sh.next
|
||||
sh.next = pre
|
||||
pre = sh
|
||||
sh = next
|
||||
}
|
||||
printList(pre)
|
||||
|
||||
p1, p2 := head, pre
|
||||
for p2 != nil {
|
||||
next1, next2 := p1.next, p2.next
|
||||
p1.next = p2
|
||||
p2.next = next1
|
||||
p1, p2 = next1, next2
|
||||
}
|
||||
printList(head)
|
||||
}
|
||||
|
||||
func TestReorderList(t *testing.T) {
|
||||
printList(makeNode(10))
|
||||
reorderList(makeNode(10))
|
||||
}
|
||||
|
||||
func printList(head *node) {
|
||||
for head != nil {
|
||||
fmt.Printf("%d->", head.value)
|
||||
head = head.next
|
||||
}
|
||||
fmt.Println("nil")
|
||||
}
|
||||
|
||||
func makeNode(count int) *node {
|
||||
var h *node = nil
|
||||
var p *node = nil
|
||||
for i := 0; i < count; i++ {
|
||||
n := &node{
|
||||
value: i,
|
||||
}
|
||||
if h == nil {
|
||||
h = n
|
||||
p = h
|
||||
} else {
|
||||
p.next = n
|
||||
p = p.next
|
||||
}
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
type node struct {
|
||||
value int
|
||||
next *node
|
||||
}
|
||||
Reference in New Issue
Block a user