```cpp class Solution { public: ListNode* swapPairs(ListNode* p) { ListNode* head = new ListNode(0, p); p = head; while (p->next && p->next->next) { ListNode* first = p->next, *second = first->next, *third = second->next; p->next = second, first->next = third, second->next = first; p = first; } return head->next; } };
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# from typing import Optional
# # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next
classSolution: defswapPairs(self, p: Optional[ListNode]) -> Optional[ListNode]: head = ListNode(0, p) p = head while p.nextand p.next.next: first, second, third = p.next, p.next.next, p.next.next.next p.next, first.next, second.next = second, third, first p = first return head.next