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.
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
// 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;
}
}
}
//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
}
方法一
一般是自己实现的方法,其他方式
是在discuss
中查找的更为优秀的方法,用作学习和借鉴。