Skip to content

Commit

Permalink
more readable implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
haoel committed Mar 30, 2019
1 parent 5db7fa4 commit 4bffdab
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions algorithms/cpp/swapNodesInPairs/swapNodesInPairs.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -71,4 +71,23 @@ class Solution {

return head;
}

ListNode* swapPairs3(ListNode* head) {
// Three pointers point current, previous and next node.
ListNode *Curr=head, *Prev=NULL, *Next=NULL;

while (Curr && Curr->next ) {
Next = Curr->next;

//swap nodes
Curr->next = Next->next;
Prev == NULL ? head = Prev = Next : Prev->next = Next;
Next->next = Curr;

//set the pointers to next place.
Prev = Curr;
Curr = Curr->next;
}
return head;
}
};

0 comments on commit 4bffdab

Please sign in to comment.