Skip to content

Commit

Permalink
Merge pull request #834 from bus710/week04
Browse files Browse the repository at this point in the history
[bus710] week 04
  • Loading branch information
bus710 authored Jan 3, 2025
2 parents cfbf61c + ae8ddaa commit b8c3521
Showing 1 changed file with 52 additions and 0 deletions.
52 changes: 52 additions & 0 deletions merge-two-sorted-lists/bus710.go
Original file line number Diff line number Diff line change
@@ -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
}

0 comments on commit b8c3521

Please sign in to comment.