[勇者闯LeetCode] 21. Merge Two Sorted Lists
Description
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.
Information
- Tags: Linked List
- Difficulty: Easy
Solution
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
temp = ListNode(0)
lt, rt, ans = l1, l2, temp
while lt or rt:
if lt is None:
temp.next, rt = rt, None
elif rt is None:
temp.next, lt = lt, None
elif lt.val < rt.val:
temp.next, lt = lt, lt.next
else:
temp.next, rt = rt, rt.next
temp = temp.next
return ans.next