题目内容
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
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
https://leetcode-cn.com/problems/merge-two-sorted-lists/
题目思路
我使用了递归的方法进行处理。每次选出一个最大的节点。然后这个节点的下个继续调用这个函数直到保证至少一个链表被调用完毕。
程序代码
# 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
"""
if not l1 or not l2:
return l1 or l2
res=ListNode(0)
head=res
if l1.val<=l2.val:
res.val=l1.val
res.next=self.mergeTwoLists(l1.next,l2)
else:
res.val=l2.val
res.next=self.mergeTwoLists(l1,l2.next)
return head