- 时间复杂度
O(M+ N)
: M
,N
分别为链表l1
,l2
的长度,合并操作需遍历两链表。 - 空间复杂度
O(1)
:节点引用dum
, cur
使用常数大小的额外空间。
Golang
package main
type ListNode struct {
Val int
Next *ListNode
}
func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode {
var dum = new(ListNode)
var cur = dum
for ; l1 != nil && l2 != nil; {
if l1.Val < l2.Val {
cur.Next = l1
l1 = l1.Next
} else {
cur.Next = l2
l2 = l2.Next
}
cur = cur.Next
}
if l1 != nil {
cur.Next = l1
} else {
cur.Next = l2
}
return dum.Next
}
Python
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
dum = cur = ListNode(0)
while l1 and l2:
if l1.val < l2.val:
cur.next = l1
l1 = l1.next
else:
cur.next = l2
l2 = l2.next
cur = cur.next
cur.next = l1 if l1 else l2
return dum.next
C#
public class ListNode
{
public int val;
public ListNode next;
public ListNode(int x) { val = x; }
}
public class Solution
{
public ListNode MergeTwoLists(ListNode l1, ListNode l2)
{
ListNode dum = new ListNode(0);
ListNode cur = dum;
while(l1 != null && l2 != null) {
if(l1.val < l2.val) {
cur.next = l1;
l1 = l1.next;
}
else {
cur.next = l2;
l2 = l2.next;
}
cur = cur.next;
}
if(l1 != null) {
cur.next = l1;
}
else {
cur.next = l2;
}
return dum.next;
}
}