Golang O(n + m) accepted solution


  • 0
    V
    func MergeTwoSortedLists(firstHead *ListNode, secondHead *ListNode) *ListNode {
    	if firstHead == nil {
    		return secondHead
    	} else if secondHead == nil {
    		return firstHead
    	}
    	var i, j, current, resultHead *ListNode
    	i = firstHead
    	j = secondHead
    
    	//don't want to check head in the loop every time, so
    	//find the first element for the result list
    	if i.Val <= j.Val {
    		current = i
    		i = i.Next
    	} else {
    		current = j
    		j = j.Next
    	}
    	resultHead = current
    
    	for i != nil || j != nil {
    		//take el from first list if value1 lower than value2 or second list is empty
    		if j == nil || (i != nil && i.Val <= j.Val) {
    			current.Next = i
    			current = i
    			i = i.Next
    		} else if j != nil {
    			current.Next = j
    			current = j
    			j = j.Next
    		}
    	}
    
    	return resultHead
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.