Leetcode Merge Sorted Lists

Source: Internet
Author: User

The merge of Leetcode problem solving and the original problem of Sorted lists

The two ordered linked lists are stitched together into an ordered list.

Note the point:

    • No additional application nodes are required, mainly linking the nodes in the original list
    • One of the original linked list is already all in the new linked list, the rest of the list can be directly spliced

Example:

Input: L1 = 1->2->4, L2 = 3
Output: 1->2->3->4

Thinking of solving problems

To avoid classification discussions, add a dummy head node. Now only two pointers are required to point to the original two linked lists, and the smaller nodes are added to the new linked list. The parameters passed in L1 and L2 can be used as pointers to traverse two linked lists.

AC Source
# 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 "" "temp = ListNode (-1) Head = Temp whileL1 andL2:ifL1.val > l2.val:temp.next = L2 L2 = L2.nextElse: temp.next = L1 L1 = L1.next temp = Temp.nextifL1:temp.next = L1Else: Temp.next = L2returnHead.nextif__name__ = ="__main__":assertSolution (). Mergetwolists (ListNode (1), ListNode (2). val = =1

Welcome to my GitHub to get the relevant source code.

Leetcode Merge Sorted Lists

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.