LeetCode Merge Two Sorted Lists 归并排序
2014-11-26 23:16
417 查看
题意:
将两个有序的链表归并为一个有序的链表。
思路:
设合并后的链表为head,现每次要往head中加入一个元素,该元素要么属于L1,要么属于L2,可想而知,此元素只能是L1或者L2的首个元素,那么进行一次比较就可以知道是谁了。操作到L1或L2其中一个已经没有元素为止,剩下的直接加到head后面。
AC代码
将两个有序的链表归并为一个有序的链表。
思路:
设合并后的链表为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代码
相关文章推荐
- Leetcode Merge Two Sorted Lists(合并两个有序表)
- [leetcode]Merge Two Sorted Lists
- LeetCode: Merge Two Sorted Lists
- LeetCode "Merge Two Sorted Lists"
- leetcode---Merge Two Sorted Lists
- Leetcode: Merge Two Sorted Lists
- Merge Two Sorted Lists[LEETCODE]
- LeetCode题解-21-Merge Two Sorted Lists
- leetcode Merge Two Sorted Lists
- LeetCode(21)Merge Two Sorted Lists
- [Leetcode题目]21. Merge Two Sorted Lists
- LeetCode|Merge Two Sorted Lists
- Leetcode_merge-two-sorted-lists
- LeetCode之Merge Two Sorted Lists
- LeetCode 21 - Merge Two Sorted Lists
- Leetcode:Merge Two Sorted Lists(Importance!)
- Leetcode-Merge Two Sorted Lists
- leetcode - Merge Two Sorted Lists
- 两个升序链表的合并 Merge Two Sorted Lists 【 leetcode】
- LeetCode Merge Two Sorted Lists