#-*-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