题目描述
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
思路
两个链表可以看成两个人手上都有一副有序的牌,然后进行比大小,我比不过你,我就拿下一张跟你比,输的牌都放在中央牌池中间。谁赢了,就把自己剩下的牌跟在牌池中。
代码
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def console(self):
output_list = []
while self:
output_list.append(self.val)
self = self.next
print(output_list, "\n")
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if l1 == None:
return l2
if l2 == None:
return l1
if l1 == None and l2 ==None:
return None
tmp = ListNode(0)
res = tmp
while l1 and l2:
if(l1.val <= l2.val):
res.next = ListNode(l1.val)
l1 = l1.next
else:
res.next = ListNode(l2.val)
l2= l2.next
res = res.next
while l1:
res.next = ListNode(l1.val)
res = res.next
l1 = l1.next
while l2:
res.next = ListNode(l2.val)
res = res.next
l2 = l2.next
res = tmp.next
del tmp
return res
def create_listnode(data):
tmp = ListNode(0)
res = tmp
for value in data:
res.next = ListNode(value)
res = res.next
res = tmp.next
del tmp
return res
if __name__ == "__main__":
# list_input_1 = create_listnode([1, 2, 4])
# list_input_1.console()
#
# list_input_2 = create_listnode([1, 3, 4])
# list_input_2.console()
list_input_1 = create_listnode([1, 3, 9])
list_input_1.console()
list_input_2 = create_listnode([8, 9, 10])
list_input_2.console()
res = Solution().mergeTwoLists(list_input_1, list_input_2)
res.console()