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++)

/**
 * 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:

  • This is my original work not totally AI generated

  • I have tested the solution thoroughly on leetcode

  • I have maintained proper PR description format

  • This is a meaningful contribution, not spam

Summary by Sourcery

New Features:

  • Implement swapPairs method using an iterative dummy-node approach to reverse nodes in groups of two.

@sourcery-ai
Copy link

sourcery-ai bot commented Oct 30, 2025

Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

Introduces an iterative solution for swapping nodes in pairs within a singly linked list by using a dummy head and three pointers (prev, cur, second) to manage pointer updates and maintain list continuity.

File-Level Changes

Change Details Files
Initialize dummy head and pointers
  • Create a dummy node pointing to the original head
  • Set prev to the dummy node and cur to head
24.Swap Nodes in Pairs.cpp
Implement pair-wise swapping loop
  • Loop while cur and cur->next are non-null
  • Identify second (cur->next) and npn (cur->next->next) nodes
  • Reverse pointers: second->next = cur, cur->next = npn
  • Link prev->next to second
24.Swap Nodes in Pairs.cpp
Advance pointers after each swap
  • Move prev to the original first node (cur)
  • Set cur to the start of the next pair (npn)
24.Swap Nodes in Pairs.cpp
Return new head
  • Return dummy.next as the head of the modified list
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 - here's some feedback:

  • The PR title says “Swap Nodes in Paris” instead of “Pairs”—please fix the typo.
  • The diff file path shows “197. Rising Temperature” which doesn’t match this swapPairs solution—update the filename to reflect the actual implementation.
  • Consider renaming the npn variable to something more descriptive (e.g. nextPair) for improved readability.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The PR title says “Swap Nodes in Paris” instead of “Pairs”—please fix the typo.
- The diff file path shows “197. Rising Temperature” which doesn’t match this swapPairs solution—update the filename to reflect the actual implementation.
- Consider renaming the `npn` variable to something more descriptive (e.g. `nextPair`) for improved readability.

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.

Implement FooBar class to alternate printing 'foo' and 'bar'.
Create FooBar class for alternating output
Implement a function to rank scores in a DataFrame.
Add function to order and rank scores
Add SQL query to find customers without a referee
@SjxSubham
Copy link
Owner

@aryaman0406 do these changes

  1. U are only allowed to add upto one single problem in a single PR...
    so delete those xtra files and add only one file that justifies ur PR description
  2. raise an ISSUE as well
  3. rename PR title with PRoper format ProblemNo. ProblemName.cpp
  4. Star the repo ⭐

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.

2 participants