Merge Two Sorted Lists


#1

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

#2

The below logic traverses through both list and builds the new list based on which element is smaller.

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode {
    if l1 == nil {
		return l2
	}
	if l2 == nil {
		return l1
	}
    
    head := &ListNode{Val : 0, Next : nil}
    phead := head
    
    for l1!=nil && l2!=nil{
        if l1.Val < l2.Val {
            head.Next = &ListNode{Val :l1.Val, Next: nil}
            l1 = l1.Next
        } else {
            head.Next = &ListNode{Val :l2.Val, Next: nil}
            l2 = l2.Next
        }
        
        head = head.Next
        
    }
    
    for l1!=nil{
        head.Next = &ListNode{Val :l1.Val, Next: nil}
        head = head.Next
        l1 = l1.Next
    }
    
    for l2!=nil{
       head.Next = &ListNode{Val :l2.Val, Next: nil}
        head = head.Next
       l2 = l2.Next
    }
    
    return phead.Next
}