[Leetcode] 21. Merge Two Sorted Lists

来源:互联网 发布:软件著作权 模块 编辑:程序博客网 时间:2024/05/27 03:30

Problem:

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.

Idea:
Basic singly-linked list operation. Use two ListNodes as pointers to point two input lists individually. Compare values of two ListNodes and then make the ListNode with smaller value move backward.

Solution:

# Definition for singly-linked list.# class ListNode(object):#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution(object):    def mergeTwoLists(self, l1, l2):        """        :type l1: ListNode        :type l2: ListNode        :rtype: ListNode        """        inode = l1        jnode = l2        if l1 == None:            head = l2            return head        elif l2 == None:            head = l1            return head        elif l1.val < l2.val:            head = l1            inode = inode.next        else:            head = l2            jnode = jnode.next        tmpnode = head        while inode != None or jnode != None:            if inode == None:                tmpnode.next = jnode                return head            elif jnode == None:                tmpnode.next = inode                return head            elif inode.val < jnode.val:                tmpnode.next = inode                tmpnode = tmpnode.next                inode = inode.next            else:                tmpnode.next = jnode                tmpnode = tmpnode.next                jnode = jnode.next        return head
0 0
原创粉丝点击