题目大意
给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
Given 1->2->3->4, you should return the list as 2->1->4->3.
输入:head = [1,2,3,4]
输出:[2,1,4,3]
解题思路
根据题目意思迭代交换链表节点即可。
代码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
# 迭代
# 空节点
LNHead = ListNode(0)
LNHead.next = head
temp = LNHead
while temp.next and temp.next.next:
# 节点交换
nodeOne = temp.next
nodeTwo = temp.next.next
temp.next = nodeTwo
nodeOne.next = nodeTwo.next
nodeTwo.next = nodeOne
temp = nodeOne
return LNHead.next