Sunday, September 7, 2014

Leetcode: Merge Two Sorted Lists @Python

Recursive solution:
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # @param two ListNodes
    # @return a ListNode
    def mergeTwoLists(self, l1, l2):
        if not l1: return l2
        if not l2: return l1
        if l1.val<l2.val:
            l1.next=self.mergeTwoLists(l1.next,l2)
            return l1
        else:
            l2.next=self.mergeTwoLists(l1,l2.next)
            return l2     
Iterative solution:
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # @param two ListNodes
    # @return a ListNode
    def mergeTwoLists(self, l1, l2):
        if not l1:
            return l2
        elif not l2:a
            return l1
        if l1.val>=l2.val:
            temp=l2
            l2=l1
            l1=temp
        crt1=l1
        crt2=l2
        if crt1.next==None:
            crt1.next=crt2
            return crt1
        while crt2:
            while crt1.val<crt2.val and crt1.next.val<crt2.val:
                crt1=crt1.next
                if not crt1.next:
                    crt1.next=crt2
                    return l1
            temp1=crt1.next
            temp2=crt2.next
            crt1.next=crt2
            crt1=crt2
            crt1.next=temp1
            crt2=temp2
        return l1       

No comments :

Post a Comment