From ae8ddaa482aab176f0f0e082459fdf43a94c5d1f Mon Sep 17 00:00:00 2001 From: bus710 Date: Fri, 3 Jan 2025 00:02:04 -0800 Subject: [PATCH] week 4 --- merge-two-sorted-lists/bus710.go | 52 ++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 merge-two-sorted-lists/bus710.go diff --git a/merge-two-sorted-lists/bus710.go b/merge-two-sorted-lists/bus710.go new file mode 100644 index 000000000..9d47a477d --- /dev/null +++ b/merge-two-sorted-lists/bus710.go @@ -0,0 +1,52 @@ +package hello + +type ListNode struct { + Val int + Next *ListNode +} + +func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode { + if list1 == nil && list2 == nil { + return nil + } else if list1 == nil { + return list2 + } else if list2 == nil { + return list1 + } + + newList := &ListNode{} + cur := newList + + for { + switch { + case list1.Val < list2.Val: + cur.Next = &ListNode{Val: list1.Val} + list1 = list1.Next + case list1.Val > list2.Val: + cur.Next = &ListNode{Val: list2.Val} + list2 = list2.Next + default: + cur.Next = &ListNode{Val: list1.Val} + list1 = list1.Next + cur = cur.Next + cur.Next = &ListNode{Val: list2.Val} + list2 = list2.Next + } + cur = cur.Next + if list1 == nil && list2 == nil && cur.Next == nil { + break + } + + if list1 == nil { + cur.Next = list2 + break + } + if list2 == nil { + cur.Next = list1 + break + } + + } + + return newList.Next +}