原題
將兩個(gè)排序鏈表合并為一個(gè)新的排序鏈表
樣例
給出 1->3->8->11->15->null叹螟,2->null,
返回 1->2->3->8->11->15->null湖员。
解題思路
- 基礎(chǔ)鏈表操作佑淀,每次比較連個(gè)鏈表的頭次询,把相對小的加入新鏈表
完整代碼
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
dummy = ListNode(0)
current = dummy
while l1 != None and l2 != None:
if l1.val < l2.val:
current.next = l1
l1 = l1.next
else:
current.next = l2
l2 = l2.next
current = current.next
if l1 != None:
current.next = l1
else:
current.next = l2
return dummy.next