From 2f9e0ea4ddd5d17777a03eeb4aa477bee0f70f5c Mon Sep 17 00:00:00 2001 From: VicRen Date: Sat, 26 Aug 2023 23:42:36 +0800 Subject: [PATCH] code kata 230826 --- code_kata_230826/reorder_list_test.go | 76 +++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 code_kata_230826/reorder_list_test.go diff --git a/code_kata_230826/reorder_list_test.go b/code_kata_230826/reorder_list_test.go new file mode 100644 index 0000000..4d1b328 --- /dev/null +++ b/code_kata_230826/reorder_list_test.go @@ -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 +}