题目描述:
给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
解题思路:
算是比较基础的链表操作,但是要捋清各个节点指针的指向,因为一次处理可能需要四个节点一起联动。
# 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]:
dhead = ListNode(0, head )
cur = dhead
while cur.next and cur.next.next :
temp1 = cur.next
temp2 = cur.next.next.next
cur.next = cur.next.next
cur.next.next= temp1
temp1.next = temp2
cur = cur.next.next
return dhead.next