Skip to content

Commit 6153874

Browse files
committed
more readable implementation
1 parent cecc733 commit 6153874

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

algorithms/cpp/swapNodesInPairs/swapNodesInPairs.cpp

+19
Original file line numberDiff line numberDiff line change
@@ -71,4 +71,23 @@ class Solution {
7171

7272
return head;
7373
}
74+
75+
ListNode* swapPairs3(ListNode* head) {
76+
// Three pointers point current, previous and next node.
77+
ListNode *Curr=head, *Prev=NULL, *Next=NULL;
78+
79+
while (Curr && Curr->next ) {
80+
Next = Curr->next;
81+
82+
//swap nodes
83+
Curr->next = Next->next;
84+
Prev == NULL ? head = Prev = Next : Prev->next = Next;
85+
Next->next = Curr;
86+
87+
//set the pointers to next place.
88+
Prev = Curr;
89+
Curr = Curr->next;
90+
}
91+
return head;
92+
}
7493
};

0 commit comments

Comments
 (0)