Can you tell me the approach both in recursion and using loop
Swap Nodes in pair
hello @anmolaggarwal.432
u just have to implement what is said. there is no special technique .
ListNode* swapPairs(ListNode* head) {
if(head == NULL)
return NULL;
if(head->next == NULL)
return head;
ListNode* next = head->next;
head->next = swapPairs(next->next);
next->next = head;
return next;
}
Can you explain a bit
Also using the abv code will make sc O(N) how to do it in O(1) please help
do it iterativley,recusrsion will always take O(N)
this is main three lines
first line we are storing second node address.
in secone line we are calling on remaining list and assigning its returned value to next of head node
and then in third line assigning head in the next of second node.
and returning second address becuase now this is the head.