您的位置:首页 > 其它

LeetCode Merge Two Sorted Lists 归并排序

2014-11-26 23:16 417 查看
题意:

  将两个有序的链表归并为一个有序的链表。

思路:

  设合并后的链表为head,现每次要往head中加入一个元素,该元素要么属于L1,要么属于L2,可想而知,此元素只能是L1或者L2的首个元素,那么进行一次比较就可以知道是谁了。操作到L1或L2其中一个已经没有元素为止,剩下的直接加到head后面。

# 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
"""
head=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
if l1:    cur.next=l1
if l2:    cur.next=l2
return head.next


AC代码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: