GeeksforGeeks » Interview Questions
Microsoft Interview Question for Software Engineer/Developer (Fresher) about Linked Lists
(10 posts)-
Reverse a Linked List in size of 2
Say LL is
1->2->3->4->5->6->7->8
Then u need to return
7->8->5->6->3->4->1->2
-
1) Reverse the Linked List (See http://www.geeksforgeeks.org/archives/860)
2) Swap the elements in pairs (See http://www.geeksforgeeks.org/archives/7049) -
@Kartik, Here is a recursive function that reverses Linked List in size 2 increments in -- 1 step only instead of two steps. Thank you. Camster
node* reversesize2(node* LL){
node* retval;
if (LL && LL->next && LL->next->next == NULL){
return LL;
}
if (LL && LL->next){
retval = reversesize2(LL->next->next);
swap(&LL,&(LL->next));
node* x = retval;
while (x->next){
x = x->next;
}
if (x){
x->next = LL->next;
x->next->next = LL;
if (x->next->next){
x->next->next->next = NULL;
}
}
return retval;
}
}void swap(node** node1, node** node2){
int tmp;
tmp = (*node1)->value;
(*node1)->value = (*node2)->value;
(*node2)->value = tmp;
} -
@camster ,can u pls explain your logic.
-
LList* reverse2(LList* head) { if(!head) return NULL; LList* res = NULL; LList* cur = head; LList* nextnext = (cur->next ? cur->next->next : NULL); while(cur) { nextnext = (cur->next ? cur->next->next : NULL); if(cur->next) { cur->next->next = res; } else { cur->next = res; } res = cur; cur = nextnext; } return res; } -
dedicated_programmer, reversesize2 uses the concept of induction. reversesize2(LL->next->next) finds the reverse linked list of size 2 of LL->next->next and then connects the return value of
reversesize2(LL).specifically returnvalue->next->next, to the return value of reversesize2(LL->next->next). It is not very complicated. Thank you Camster, -
Initially,root and newroot are root nodes
struct node* reverse(struct node *root,struct node **newroot) { struct node *temp,*start; if(!root) return NULL; if(root->next && root->next->next) { temp=root; start=reverse(root->next->next,newroot); start->next->next=temp; temp->next->next=NULL; } else *newroot=root; return root; } -
Dedicated_Programmer. I just tested your reverse function on the test case below and your reverse function returns the wrong value. Plz fix it. Thank you.
Say LL is
1->2->3->4->5->6->7->8
Then u need to return
7->8->5->6->3->4->1->2
-
camster, I have again checked the code, but it is returning the output 7->8->5->6->3->4->1->2 .
As i have mentioned newroot contains the address of the root node.
Pls check it. I am waiting to hear from you.
Thank you.
Dedicated Programmer -
Dedicated Programmer, I tested your code. You proposed solution modifies the pointer to pointer new root. IMHO, Ny solution is better than yours because I return the reversed size-2 list wheras your return value is returns 7->8->NULL. Plz correct ur solution or elese I can do it for you ig you pay me $50/hour. Thank you,
Reply
You must log in to post.