Skip to content

Conversation

@aryaman0406
Copy link

@aryaman0406 aryaman0406 commented Oct 30, 2025

PR Title Format: 24.Swap Nodes in Pairs.cpp

💡 Intuition
The core idea is to perform a group-wise reversal of linked list nodes, where each group has a size of two. Since the node pointers must be correctly updated to maintain the list structure, an iterative approach using a dummy node simplifies the logic, especially the handling of the new head and linking the swapped pair back to the previous segment of the list.

✍️ Approach
This solution uses an iterative approach with a dummy head node and three pointers to manage the swapping: prev, cur (the first node of the pair), and second (the second node of the pair).

Dummy Node Initialization: A dummy node is created and points to the original head. This node acts as a fixed starting point and simplifies the logic for updating the pointer that precedes the swapped pair. The pointer prev is initialized to point to the dummy node.

Iteration Setup: The pointer cur is initialized to the head of the list. The loop continues as long as a valid pair exists: while (cur && cur->next).

Swapping Steps (within the loop):

Identify: Identify the critical nodes:

second: The second node of the pair (cur->next).

npn (Next Pair Node): The first node of the next pair (cur->next->next). This is stored so we don't lose the rest of the list.

Reverse Pointers:

Link the second node to the first: second->next = cur; (Swap)

Link the original first node to the next unswapped segment: cur->next = npn; (Maintain continuity)

Link the preceding node to the new first node (which is second): prev->next = second; (Attach the swapped pair)

Advance Pointers:

prev moves to the unswapped node (cur), which is now the end of the swapped pair.

cur moves to the start of the next pair (npn).

Return: After the loop completes, the new head of the list is dummy.next.

Code Solution (C++)
C++

/**

  • 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) {}

  • };
    /
    class Solution {
    public:
    ListNode
    swapPairs(ListNode* head) {
    // Create a dummy node to act as the predecessor to the head
    ListNode dummy(0, head);
    ListNode *prev = &dummy;
    ListNode *cur = head;

     // Loop while there is at least one pair remaining (cur and cur->next are non-null)
     while (cur && cur->next) {
         // 1. Identify critical nodes for swapping
         ListNode *second = cur->next; 
         ListNode *npn = cur->next->next; // Start of the next pair
    
         // 2. Perform the swap
         second->next = cur;     // Point second node to first node (cur)
         cur->next = npn;        // Point first node to the next pair's start (npn)
         prev->next = second;    // Link the previous segment to the new pair's start (second)
    
         // 3. Advance pointers for the next iteration
         prev = cur;             // The original first node (cur) is now the predecessor for the next swap
         cur = npn;              // Move to the start of the next pair
     }
    
     return dummy.next;        
    

    }
    };
    🔗 Related Issues
    By submitting this PR, I confirm that:

[x] This is my original work not totally AI generated

[x] I have tested the solution thoroughly on leetcode

[x] I have maintained proper PR description format

[x] This is a meaningful contribution, not spam

Summary by Sourcery

New Features:

  • Add swapPairs function to swap adjacent nodes in a linked list in C++ using a dummy head and pointer manipulation.

@sourcery-ai
Copy link

sourcery-ai bot commented Oct 30, 2025

Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

Introduced a new C++ implementation of swapPairs using an iterative dummy-head approach that performs in-place pairwise node swaps in a singly-linked list.

File-Level Changes

Change Details Files
Implement swapPairs using an iterative three-pointer technique
  • Initialize dummy head and pointers (prev, cur)
  • Add loop to process nodes while cur and cur->next exist
  • Identify pair nodes (second, npn) and update next pointers to swap
  • Advance prev to cur and cur to npn for next iteration
  • Return new head via dummy.next
24.Swap Nodes in Pairs.cpp

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey there - I've reviewed your changes and they look great!


Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant