leetcode with python:24. Swap Nodes in Pairs

好耶不知不觉就来到第100篇文了
之后medium题的占比会越来越高吧
庆祝一下就来继续写文了XD
希望未来也能继续持续下去

题目:

Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)

给定一个linked list,对每两个连续node进行交换
而且是要Node的变动,不能只是值的交换而已
ex:input: [1,2,3,4]=>output: [2,1,4,3]

这题用递迴来实作

# Definition for singly-linked list.# class ListNode:#     def __init__(self, val=0, next=None):#         self.val = val#         self.next = nextclass Solution:    def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:        if head and head.next:            temp=head            temp2=head.next.next            head=head.next            head.next=temp            head.next.next=self.swapPairs(temp2)         return head

先确定head和head.next都不为None(确认有两个Node进行交换)
用temp存取head,temp2存取head.next.next(下一次交换的head)

接着将head改为head.next,head.next透过temp变为原head
让结构变为原head.next->原head

完成了一次交换,接下来进行下一次
用temp2存好的原head.next.next进行递迴
使其变为新head.next.next(已进行完交换)

整个过程完成后回传新head
刚好递迴最外层回传的是新linked list的头
最后执行时间24ms(faster than 99.47%)

那我们下题见


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章