code kata 230827

This commit is contained in:
VicRen
2023-08-27 11:30:48 +08:00
parent 2f9e0ea4dd
commit 0354f1103b
2 changed files with 102 additions and 0 deletions

View File

@@ -42,6 +42,7 @@ func reorderList(head *node) {
func TestReorderList(t *testing.T) { func TestReorderList(t *testing.T) {
printList(makeNode(10)) printList(makeNode(10))
reorderList(makeNode(10)) reorderList(makeNode(10))
reorderList2(makeNode(21))
} }
func printList(head *node) { func printList(head *node) {
@@ -52,6 +53,36 @@ func printList(head *node) {
fmt.Println("nil") 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 { func makeNode(count int) *node {
var h *node = nil var h *node = nil
var p *node = nil var p *node = nil

View 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
}