[Leetcode] [Python]21:merge Sorted Lists

Source: Internet
Author: User

#-*-Coding:utf8-*-
‘‘‘
__author__ = ' [email protected] '

21:merge Sorted Lists
https://oj.leetcode.com/problems/merge-two-sorted-lists/

Merge sorted linked lists and return it as a new list.
The new list should is made by splicing together the nodes of the first of the lists.

===comments by dabay===
The operation of the basic list. First, make a head node and use two pointers to record the position of the two linked lists.
Compare the nodes of two linked lists, put the small one behind, and move the pointer afterwards.
Finally, when a list has been compared, hang up the rest of the list.
‘‘‘

# Definition for singly-linked list.
Class ListNode:
def __init__ (self, x):
Self.val = X
Self.next = None

Class Solution:
# @param the Listnodes
# @return A ListNode
def mergetwolists (self, L1, L2):
node = root = ListNode (0)
Node1 = L1
Node2 = L2
While Node1 and Node2:
If Node1.val < node2.val:
Node.next = Node1
Node1 = Node1.next
Else
Node.next = Node2
Node2 = Node2.next
node = Node.next
If Node1:
Node.next = Node1
Else
Node.next = Node2
Return Root.next


def main ():
Sol = solution ()
L1 = ListNode (1)
L2 = ListNode (2)
merged = sol.mergetwolists (L1, L2)
node = merged
While node:
Print "%s"% Node.val,
Print "End"


if __name__ = = ' __main__ ':
Import time
Start = Time.clock ()
Main ()
Print "%s sec"% (Time.clock ()-start)

[Leetcode] [Python]21:merge Sorted Lists

Related Article

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.