题目
思路
- 建立虚头节点
- 仅判断存在2个next节点即可,然后替换
代码
# 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]:
pre_head = ListNode(val=-1,next=head) # 虚头节点
current_head = pre_head
while current_head.next and current_head.next.next: # 若存在2个next节点则替换
temp_node = current_head.next.next.next
node1 = current_head.next
node2 = current_head.next.next
current_head.next = node2
current_head.next.next = node1
current_head.next.next.next = temp_node
current_head = current_head.next.next
return pre_head.next