From 0354f1103bb6750149895790725ae0ddefcf4f60 Mon Sep 17 00:00:00 2001 From: VicRen Date: Sun, 27 Aug 2023 11:30:48 +0800 Subject: [PATCH] code kata 230827 --- code_kata_230826/reorder_list_test.go | 31 ++++++++++++ code_kata_230827/reorder_list_test.go | 71 +++++++++++++++++++++++++++ 2 files changed, 102 insertions(+) create mode 100644 code_kata_230827/reorder_list_test.go diff --git a/code_kata_230826/reorder_list_test.go b/code_kata_230826/reorder_list_test.go index 4d1b328..a8d36e9 100644 --- a/code_kata_230826/reorder_list_test.go +++ b/code_kata_230826/reorder_list_test.go @@ -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 diff --git a/code_kata_230827/reorder_list_test.go b/code_kata_230827/reorder_list_test.go new file mode 100644 index 0000000..ba34c74 --- /dev/null +++ b/code_kata_230827/reorder_list_test.go @@ -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 +}