I have this programming question -
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
And I wrote these two programs, in one I am changing just the values and in other I am changing connections itself.
FIRST program
/**
* 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) {
ListNode* p = head;
int temp = 0;
while(p!= NULL && p->next!=NULL)
{
temp = p->val;
p->val = p->next->val;
p->next->val = temp;
p = p->next->next;
}
return head;
}
};
SECOND Program
/**
* 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) {
ListNode* p = head;
ListNode* q = head;
ListNode* r = head;
int flag = 0;
while(p!= NULL && p->next!=NULL)
{
if(flag == 0)
{
flag = 1;
q = p->next;
p->next = q->next;
q->next = p;
head = q;
p = q->next->next;
r = q->next;
continue;
}
q = p->next;
p->next = q->next;
q->next = p;
r->next = q;
p = q->next->next;
r = q->next;
}
return head;
}
};
When I submitted this code, I found the second is having lesser runtime and is using lesser memory. But in the first one I am just swapping values and using an extra pointer and an extra integer variable, but in second one I am using 3 extra pointers. How can second one be more efficient?