【LeetCode】24.两两交换链表中的节点

24.两两交换链表中的节点

知识点:链表

题目描述

给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。

示例
示例 1:
输入:head = [1,2,3,4]
输出:[2,1,4,3]

示例 2:
输入:head = []
输出:[]

示例 3:
输入:head = [1]
输出:[1]


解法一:迭代

两两交换链表中的节点,所以每次都需要成对的,并且要判断一下这成对的后面是不是成对的
if是,那能够继续循环
if不是,那证明后面只有一个或者没有了,处理一下末尾即可了

class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        if not head or not head.next:
            return head
        pre = head
        cur = head.next
        dummyhead = cur
        while cur.next and cur.next.next:
            next_node = cur.next
            cur.next = pre
            pre.next = next_node.next
            pre = next_node
            cur = next_node.next
        last = cur.next
        cur.next = pre
        pre.next = last
        return dummyhead