咕咕咕,之前忙着看Django,又咕了leetcode好多天,今天开始每天一题leetcode加题解启动(发出了不咕咕咕的叫声
今天的题目是这样的
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
题意清晰,是一道关于链表的入门题
在这里先写一下在python中链表的定义,由于python中没有指针这个概念,所以在python中使用一个链表节点类来定义链表
class ListNode():
def __init__(self,value,next = None):
self.val = value
这样next这个类属性就指向了下一个ListNode类,实现了链表的效果
现在重新来看题目
两个已经排好序的链表,然后重新组合成一个新的链表,那只要逐一对比两个老链表,然后让新链表指向两个老链表的节点就可以了,下面是代码
# 执行用时 : 36 ms, 在Merge Two Sorted Lists的Python提交中击败了50.40% 的用户
# 内存消耗 : 11.8 MB, 在Merge Two Sorted Lists的Python提交中击败了0.57% 的用户
# 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
"""
#创建一个新的链表的头
first = ListNode(0)
head = first
#当两个老链表有一个都不为空时执行
while l1 and l2:
if l1.val >= l2.val:
head.next = l2
l2 = l2.next
else:
head.next = l1
l1 = l1.next
head = head.next
if l1 is not None:
head.next = l1
if l2 is not None:
head.next = l2
return first.next