Interview Questions

Given 2 linked lists, merge them in-plac....

Microsoft Interview Questions and Answers


(Continued from previous question...)

71. Given 2 linked lists, merge them in-plac....

Question:
Given 2 linked lists, merge them in-place, so that 1st element is from list1, 2nd from list2, 3rd from list1, 4th from list2, and so on..


maybe an answer:

struct Node {
Node * next;
};

Node * merge(Node * x, Node * y) {
Node ret;
ret.next = NULL;

Node * p = &ret;

while (x != NULL && y != NULL) {
p->next = x;
x = x->next;
p = p->next;

p->next = y;
y = y->next;
p = p->next;
}

if (x != NULL)
p->next = x;
else if (y != NULL)
p->next = y;

return ret.next;
}



maybe an answer2:

// length of linked list shoud be same if not then not possible to alternate nodes

struct node* mergerlinkedlist(struct node*l1,struct node *l2)
{
struct node *temp=NULL:
struct node *head;
struct node *temp1;
struct node *temp2;
int c;
temp1=l1;
temp2=l2;
c=1;
while(temp1 && temp2)
{
if(c)
{
if(!head)
{
head=temp1;
temp1=temp1->next;
head->next=NULL;
temp=head;
}
else
{
temp->next=temp1;
temp=temp1;
temp1=temp1->next;
temp->next=NULL;

}
c=0;
}
else
{
temp->next=temp2;
temp2=temp2->next;
temp=temp->next;
c=1;
}

}
}

(Continued on next question...)

Other Interview Questions