版权声明:本文为博主原创文章,转载请联系作者获得授权并注明出处。 https://blog.csdn.net/qq_34172340/article/details/84203588
数据结构和算法,是编程的基础,想要提高编程能力,这是绕不开的坎,为了练习算法,在Codewars和LeetCode上刷了一些难度级别为easy的题,代码都保存成py文件了,时间久了,积累的多了,有些乱,接下了打算逐步把它们搬到博客上来,整理一下,便于查找复习。废话少说,开工!
试题
1、将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
解题思路:
1,创建一个新的空链表k;
2,对2个单向链表(a,b)进行遍历,逐个取出所有的元素进行对比;
3,a[1]>b[1],则把b[1]加入k,往后走到b[2],再和a[1]对比,大,则添加a[1]到k的尾部,一直循环对比,把较小的值添加到k的尾部,如果相等,则都添加;
4,直到a和 b有一个到达尾部,或者同时到达尾部,若只有一个到达尾部,则遍历另一个链表,把里面的元素逐个加入到k的尾部,
2个同时到达尾部,则结束,返回k
解题代码:
这道题逻辑很清晰,麻烦的地方在于链表并不像列表一样,是内置的数据类型,可以使用list方法直接创建,需要自己手动创建
首先要创建链表节点及方法,并添加一些数据
class ListNode:
"""
创建节点
"""
def __init__(self, x):
self.val = x
self.next = None
创建链表的方法
这里只需要添加元素方法和遍历方法(最后查看用)就可以了,
class SingleLinkList:
def __init__(self):
self._head = None
def append(self, item):
"""尾部添加元素"""
node = ListNode(item)
# 先判断链表是否为空,若是空链表,则将_head指向新节点
if self.is_empty():
self._head = node
node.next = None
# 若不为空,则找到尾部,将尾节点的next指向新节点
else:
cur = self._head
while cur.next != None:
cur = cur.next
cur.next = node
def is_empty(self):
"""判断链表是否为空"""
return self._head == None
def travel(self):
"""遍历链表"""
if self.is_empty():
return
cur = self._head
print('cur.val',cur.val)
while cur.next != None:
cur = cur.next
print('cur.val', cur.val)
合并链表代码
class Solution():
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
# 创建新链表
newnode = SingleLinkList()
cur1 = l1._head
cur2 = l2._head
while (cur1 != None) and (cur2 != None):
if cur1.val < cur2.val:
newnode.append(cur1.val)
cur1 = cur1.next
elif cur1.val > cur2.val:
newnode.append(cur2.val)
cur2 = cur2.next
else:
newnode.append(cur1.val)
newnode.append(cur2.val)
cur1 = cur1.next
cur2 = cur2.next
else:
if cur1 == None:
while cur2 != None:
newnode.append(cur2.val)
cur2 = cur2.next
elif cur2 == None:
while cur1 != None:
newnode.append(cur1.val)
cur1 = cur1.next
return newnode
验证结果
创建链表,并添加元素(注意:因为要求是有序链表,所以添加元素时要按顺序)
if __name__ == "__main__":
sl1 = SingleLinkList()
sl1.append(2)
sl1.append(6)
sl1.append(9)
sl1.append(14)
sl1.append(36)
sl2 = SingleLinkList()
sl2.append(3)
sl2.append(8)
sl2.append(9)
sl2.append(12)
sl2.append(22)
sl2.append(35)
# 调用函数,result接收返回值
res = Solution()
result = res.mergeTwoLists(sl1, sl2)
# 遍历验证
result.travel()
遍历结果:
cur.val 2
cur.val 3
cur.val 6
cur.val 8
cur.val 9
cur.val 9
cur.val 12
cur.val 14
cur.val 22
cur.val 35
cur.val 36