Cover image for LeetCode Hot 100 P24 Swap Nodes in Pairs

LeetCode Hot 100 P24 Swap Nodes in Pairs

Words 176
Views
Visitors

Timeline

Timeline

2026-03-14

init

linked list

Problem:

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode() : val(0), next(nullptr) {} *     ListNode(int x) : val(x), next(nullptr) {} *     ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */struct ListNode {        int val;        ListNode *next;        ListNode()                : val(0)                , next(nullptr)        {        }        ListNode(int x)                : val(x)                , next(nullptr)        {        }        ListNode(int x, ListNode *next)                : val(x)                , next(next)        {        }};class Solution {    public:        ListNode *swapPairs(ListNode *head)        {                ListNode *virtual_head = new ListNode(0, head);                ListNode *prev = virtual_head, *curr = prev->next, *next, *next_next;                while (curr) {                        next = curr->next;                        if (next == nullptr) // Single node, no need to swap                                break;                        next_next = next->next;                        prev->next = next;                        next->next = curr;                        curr->next = next_next;                        prev = curr;                        curr = next_next;                }                head = virtual_head->next;                delete virtual_head;                return head;        }};
Loading comments…