Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
LeetCode/merge-two-sorted-lists
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
102 lines (93 sloc)
2.87 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. | |
Example: | |
Input: 1->2->4, 1->3->4 | |
Output: 1->1->2->3->4->4 | |
# Definition for singly-linked list. | |
# class ListNode: | |
# def __init__(self, x): | |
# self.val = x | |
# self.next = None | |
class Solution: | |
def mergeTwoLists(self, l1, l2): | |
""" | |
:type l1: ListNode | |
:type l2: ListNode | |
:rtype: ListNode | |
""" | |
if l1==None: | |
return l2 | |
if l2==None: | |
return l1 | |
start_node=ListNode(0) | |
head=start_node | |
length=2 | |
test=l1 | |
while test.next!=None: | |
length+=1 | |
test=test.next | |
test=l2 | |
while test.next!=None: | |
length+=1 | |
test=test.next | |
count=0 | |
flag_l1=False | |
flag_l2=False | |
while count<length: | |
if count==0: | |
if l1.val<l2.val: | |
start_node.val=l1.val | |
if l1.next!=None: | |
l1=l1.next | |
else: | |
flag_l2=True | |
else: | |
start_node.val=l2.val | |
if l2.next!=None: | |
l2=l2.next | |
else: | |
flag_l1=True | |
count+=1 | |
else: | |
if l1.val<l2.val: | |
value=l1.val | |
if l1.next!=None: | |
l1=l1.next | |
else: | |
flag_l2=True | |
else: | |
value=l2.val | |
if l2.next!=None: | |
l2=l2.next | |
else: | |
flag_l1=True | |
tmp_node=ListNode(value) | |
start_node.next=tmp_node | |
start_node=tmp_node | |
count+=1 | |
if flag_l1: | |
while l1.next!=None: | |
value=l1.val | |
tmp_node=ListNode(value) | |
start_node.next=tmp_node | |
start_node=tmp_node | |
l1=l1.next | |
count+=1 | |
value=l1.val | |
tmp_node=ListNode(value) | |
start_node.next=tmp_node | |
count+=1 | |
if flag_l2: | |
while l2.next!=None: | |
value=l2.val | |
tmp_node=ListNode(value) | |
start_node.next=tmp_node | |
start_node=tmp_node | |
l2=l2.next | |
count+=1 | |
value=l2.val | |
tmp_node=ListNode(value) | |
start_node.next=tmp_node | |
count+=1 | |
return head | |
Solution: | |
https://leetcode.com/problems/merge-two-sorted-lists/ |