Microsoft Interview Question
Software Engineer in Testsnode* Reverse(struct node* current) {
struct node* result = NULL;
struct node* next;
while (current != NULL) {
next = current->next; // tricky: note the next node
current->next = result; // move the node onto the result
result = current;
current = next;
}
return result
}
You do not need the result ptr.
Your function should take a reference to the head pointer, you should advance it during the operation and your tail will be your new head.
It is not asked to keep the original list and create a clone which is the reversed version. So you may simply modify the original list.
2 answers rec and iterative. No null pointer check, you can add it.
node* reverseLinkedList(node* input){
node* temp=NULL;
node* first=NULL;
if(input->next!=NULL)
temp=reverseLinkedList(input->next);
else
return input;
input->next->next=input;
input->next=NULL;
return temp;
}
node* reverseLinkedListIterative(node* input){
node* result=NULL;
node* next=NULL;
while(input!=NULL){
next=input->next;
input->next=result;
result=input;
input=next;
}
return result;
}
I checked this code is working fine ..
void reverserLinkedList(Node **head)
{
Node *prev=NULL,*tmp=NULL;
while(*head)
{
tmp = (*head)->next;
(*head)->next = prev;
prev = *head;
*head = tmp;
}
*head = prev;
}
reverse(node *p)
- Umang akash February 13, 2010{
node *q,*x;
q=NULL:
for(i=0;1<linklength;i++)
{
x=p;
while(x->next !=p)
{
x=x->next;
}
printf("%d",x->info);
p=x;
}