leetcode24. 两两交换链表中的节点
题目描述
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1:
输入:head = [1,2,3,4]
输出:[2,1,4,3]
示例 2:
输入:head = []
输出:[]
示例 3:
输入:head = [1]
输出:[1]
提示:
链表中节点的数目在范围 [0, 100] 内
0 <= Node.val <= 100
链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs
解题思路
通过迭代的方式,不断用之前的pre接上second,之后转换当前first和second的身份,并让pre等于转换身份后的first。
最后输出第一个second。
解题代码
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
pre, first, second = ListNode(0, head), head, head.next
new_head = second
while first and second:
# second要先起到领导位置
pre.next = second
# 注意下面这一步,要让first和second的身份对调
first.next, second.next = second.next, first
# 此时pre为已经是退位的的first
pre = first
if pre.next and pre.next.next:
first = pre.next
second = pre.next.next
else:
first = second = None
return new_head
执行结果
执行结果:通过
执行用时:32 ms, 在所有 Python3 提交中击败了66.50%的用户
内存消耗:15 MB, 在所有 Python3 提交中击败了48.65%的用户
共有 0 条评论