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