题目
. - 力扣(LeetCode)
给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
思路
一定要使用虚拟头节点,将虚拟头节点的下个节点指向head
两两交换即使cur的下个节点指向2,再由2指向1,再由1指向3
那就
直接将1暂定义为temp1,2定义为temp2,3定义为temp3
cur.next指向temp2,cur.next.next指向temp1,cur.next.next.next指向temp3
再将cur指向到最新的节点即可
代码
# 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: Optional[ListNode]) -> Optional[ListNode]:
if not head:
return
phead= ListNode()
phead.next = head
cur = phead
while cur.next and cur.next.next:
temp1 = cur.next
temp2 = cur.next.next
temp3 = cur.next.next.next
cur.next = temp2
cur.next.next = temp1
cur.next.next.next = temp3
cur = cur.next.next
return phead.next #最后返回一定要返回虚拟节点的下一个节点,即头节点,否则返回结果将缺少头节点