leetcode.com-problemset-all-021 - Merge Two Sorted Lists

- 3 mins

题目描述

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

PHP实现

方法一

// 4ms
/**
 * Definition for a singly-linked list.
 * class ListNode {
 *     public $val = 0;
 *     public $next = null;
 *     function __construct($val) { $this->val = $val; }
 * }
 */
class Solution {

    /**
     * @param ListNode $l1
     * @param ListNode $l2
     * @return ListNode
     */
    function mergeTwoLists($l1, $l2) {
        if($l1 === NULL) return $l2;
        if($l2 === NULL) return $l1;
        
        if($l1->val < $l2->val) {
            $l1->next = $this->mergeTwoLists($l1->next, $l2);
            return $l1;
        } else {
            $l2->next = $this->mergeTwoLists($l2->next, $l1);
            return $l2;
        }
    }
}

其他方法


Go实现

方法一

//0ms

/**
 * 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
	}

	if l1.Val < l2.Val {
		l1.Next = mergeTwoLists(l1.Next, l2)
		return l1
	} else {
		l2.Next = mergeTwoLists(l2.Next, l1)
		return l2
	}
}

其他方法

//4ms
func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode {
    if l1 == nil {
        return l2
    }
    
    var cur *ListNode = new (ListNode)
    cur = l1
    for cur != nil && l2 != nil {
        var temp *ListNode = new (ListNode)
        if cur.Val >= l2.Val {
            temp.Val = cur.Val
            temp.Next = cur.Next
            cur.Val = l2.Val
            cur.Next = temp
            
            cur = cur.Next
            l2 = l2.Next
        }else{
            if cur.Next == nil {
                cur.Next = l2
                return l1
            }else{
                cur = cur.Next
            }
        }
    }
    return l1
}

PS

rss facebook twitter github gitlab youtube mail spotify lastfm instagram linkedin google google-plus pinterest medium vimeo stackoverflow reddit quora quora