Microsoft Interview Question
Software Engineer in Testsvoid reverse_list()
{
struct list *temp;
temp=head;
if(head!=NULL & head->next!=NULL)
{
head=head->next;
reverse_list();
temp->next->next=temp;
temp->next=NULL
}
display()
}
----------------------Iterative solution----------------------
void reverse()
{
struct list *temp, *temp1;
if(head==NULL)
pf("no nodes");
temp=head->next; //temp is the new head->next
head->next=NULL //head ka next is now null
temp1=temp->next;//temp storage to move to head -> next ->next
temp->next=head; //restore new temp to point to head
head=temp; //temp is the new head
temp=temp1; //temp1 is the new temp
display();
}
Node Reverse(Node n)
{
if(n.next != null)
{
Node t = Reverse(n.next);
AddAtEnd(t, n);
return t;
}
else return n;
}
void AddAtEnd(Node t, Node n)
{
Node k = t;
while(k.next != null) k = k.next;
k.next = n;
}
#include <stdio.h>
#include <malloc.h>
typedef struct list{
struct list *next;
int val;
}list;
list *root=NULL;
void alloc(list **node, int val)
{
*node = (list *)malloc(sizeof(list));
(*node)->next=NULL;
(*node)->val = val;
}
void BuildLinkedList()
{
int i;
int len=0;
list *end, *temp;
printf("Enter the number of elements:");
scanf(" %d",&len);
for(i=0;i<len; i++)
{
if(root == NULL)
{
alloc(&root,i+1);
end = root;
continue;
}
else
alloc(&temp, i+1);
end->next = temp;
end = temp;
}
}
void PrintList(void)
{
list *temp = root;
while(temp != NULL)
{
printf(" %d", temp->val);
temp = temp->next;
}
printf("\n");
}
list * ReverseLinkedList(list *temp)
{
list *t;
if(temp == NULL)
{
printf("Empty Linked List\n");
return NULL;
}
if(temp->next != NULL)
t = ReverseLinkedList(temp->next);
else return temp;
temp->next->next = temp;
if(temp == root)
temp->next = NULL;
return t;
}
int main(void)
{
BuildLinkedList();
PrintList();
root = ReverseLinkedList(root);
PrintList();
}
Recursive Option:
//pass argument such as (linkList, NULL) in the beginning.
Node* ReverseLinkList( Node *list, Node *mergeList)
{
Node* nextNode = NULL;
nextNode = list->next;
//list should never reach NULL, so don't worry about this.
list->next = mergeList;
if(nextNode != NULL) return ReverseLinkList1(nextNode, list);
else return list;
}
see www,,careercup,,com__question?id=388843
- Anonymous February 23, 2010