LeetCode Notes_#21 Merge Two Sorted Lists
Contents
题目
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
感觉他的题目过于简单,有一些会模糊的地方没有讲清楚
- 输入是包含长度不同的情况的,这个要考虑;最后剩下的那一部分,直接连在最后
- 最后输出的整个链表也必须是顺序的(由小到大)
思路和解答
思路
思路其实跟之前的2.Add Two Numbers类似,操作链表的套路都是这样.但是不能完全抄过来,考虑一下特殊的部分
解答
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
dummyHead=ListNode(0)
p=l1
q=l2#两个链表的长度不同怎么办?
tmpNode=dummyHead
while(p!=None and q!=None):
a=p.val
b=q.val
if a>=b:
tmpNode.next=ListNode(b)
q=q.next
else:
tmpNode.next=ListNode(a)
p=p.next
tmpNode=tmpNode.next
tmpNode.next=p if p!=None else q
return dummyHead.next