Swap Nodes in Pairs using recursion in cpp
Swap Nodes in pairs in a given Linked List using Recursion
In this problem, we have a Linked List and we have to swap its Nodes in pairs. Also, we have to change only the nodes, we can't change the values of a node.
Example,
Given Linked List is 1->2->3->4->NULL
Final Linked List is 2->1->4->3->NULL
Example 2,
Given Linked List is 1->2->3->4->5->NULL
Final Linked List is 2->1->4->3->5->NULL
We will do this code using recursion in C++.
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(head==NULL)
return NULL;
if(head->next==NULL)return head;
ListNode* p1=head;
ListNode* p2=p1->next;
ListNode* p3=p2->next;
p2->next=p1;
p1->next=swapPairs(p3);
return p2;
}
};
Comments
Post a Comment