DEV Community

hamza72x
hamza72x

Posted on • Updated on

[Grind 169] 3. Merge Two Sorted Lists

Problem Link: https://leetcode.com/problems/merge-two-sorted-lists/

Solution:

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode {

    var node = &ListNode{}
    var tail = node

    for {
        if list1 == nil || list2 == nil {
           break 
        }

        if list1.Val < list2.Val {
            tail.Next = list1
            list1 = list1.Next
        } else {
            tail.Next = list2
            list2 = list2.Next
        }

        tail = tail.Next
    }

    if list1 != nil {
        tail.Next = list1
    } else if list2 != nil {
        tail.Next = list2
    }


    return node.Next
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)