Skip to content

Commit

Permalink
Create 0023-merge-k-sorted-lists.go
Browse files Browse the repository at this point in the history
  • Loading branch information
AP-Repositories authored Jan 1, 2023
1 parent 0cb22b5 commit 37ad59c
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions go/0023-merge-k-sorted-lists.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
func mergeKLists(lists []*ListNode) *ListNode {
if lists == nil || len(lists) == 0 {
return nil
}

for len(lists) > 1 {
var mergedLists []*ListNode
for i := 0; i < len(lists); i += 2 {
l1 := lists[i]
var l2 *ListNode
if (i + 1) < len(lists) {
l2 = lists[i + 1]
}
mergedLists = append(mergedLists, mergeList(l1, l2))
}
lists = mergedLists
}
return lists[0]
}

func mergeList(l1, l2 *ListNode) *ListNode {
dummy := &ListNode{}
tail := dummy

for l1 != nil && l2 != nil {
if l1.Val < l2.Val {
tail.Next = l1
l1 = l1.Next
} else {
tail.Next = l2
l2 = l2.Next
}
tail = tail.Next
}
if l1 != nil {
tail.Next = l1
}
if l2 != nil {
tail.Next = l2
}
return dummy.Next
}

0 comments on commit 37ad59c

Please sign in to comment.