Interview Question
Country: United States
At last when you are passing the address of the node then the function call's syntax should be changed, It should be pointer to pointer to the head that is list **head.
This code still has issues since we are not modifying the start of the linked list which will get modified too in case of swapping 1st and 2nd node of the linked list
procedure(Node start){
if(start == null) return;
boolean startNodeModifed = false;
Node x = start;
Node y = x.next;
while(x!= null and y != null)
{
x.next = y.next;
y.next = x;
if(!startNodeModifed)
start = y;
x = x.next;
if(x == null) return;
y = x.next;
}
}
void swp(llist *head)
{
llist *a,*b;
if(head->next==NULL || head->next->next==NULL) return;
a=head;
b=head->next;
int tmp=a->x;
a->x=b->x;
b->x=tmp;
if(b->next!=NULL)
swp(b->next);
return;
}
full code here:
#include<iostream>
using namespace std;
struct llist{
int x;
llist *next;
llist()
{
next=NULL;
}
};
void swp(llist *head)
{
llist *a,*b;
if(head->next==NULL || head->next->next==NULL) return;
a=head;
b=head->next;
int tmp=a->x;
a->x=b->x;
b->x=tmp;
if(b->next!=NULL)
swp(b->next);
return;
}
main()
{
llist *lst, *tr;
lst=new llist;
tr=lst;
cout<<"Enter number of nodes: ";
int n,x;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>x;
lst->x=x;
lst->next=new llist();
lst=lst->next;
}
swp(tr);
cout<<endl;
while(tr->next!=NULL)
{
cout<<tr->x<<" ";
tr=tr->next;
}
}
input-output:
Enter number of nodes: 5
2 5 9 6 7
5 2 6 9 7
Code:
void SwapNodes(Node** start)
{
if (start == NULL || *start == NULL)
return;
Node* temp = *start;
if (temp ->next != null)
{
*start = temp->next;
while (temp && temp->next)
{
Node* next = temp->next->next;
Node* temp2 = temp->next;
temp2->next = temp;
temp->next = next;
temp = next;
}
}
}
typedef struct ListNode
{
int val;
ListNode *next;
};
ListNode* swap(ListNode *head)
{
if (!head)
return NULL;
ListNode *node = head;
ListNode *next = node->next;
if (!next)
return head;
head = next;
ListNode *prev = NULL;
do
{
node->next = next->next;
next->next = node;
if (prev)
prev->next = next;
prev = node;
} while ((node=node->next) && (next=node->next));
return head;
}
void main(void)
{
ListNode *h = new ListNode;
h->val = 1;
h->next = NULL;
ListNode *t = h;
for (int i=2; i<=13; ++i)
{
t->next = new ListNode;
t->val = i;
t = t->next;
}
t->next = NULL;
ListNode *n = NULL;
for (n=h; n; n=n->next)
cout << n->val << " " ;
cout << endl;
h = swap(h);
for (n=h; n; n=n->next)
cout << n->val << " " ;
cout << endl;
system("pause");
}
swap first two nodes and then call recursively for the rest of the linked list
- Amit August 04, 2013