Amazon Interview Question
Software Engineer / Developersvoid RecursiveReverse(struct node** headRef) {
struct node* first;
struct node* rest;
if (*headRef == NULL) return; // empty list base case
first = *headRef; // suppose first = {1, 2, 3}
rest = first->next; // rest = {2, 3}
if (rest == NULL) return; // empty rest base case
RecursiveReverse(&rest); // Recursively reverse the smaller {2, 3}
// after: rest = {3, 2}
// put the first elem on the end of the list
first->next->next = first;
first->next = NULL; // (tricky step -- make a drawing)
*headRef = rest; // fix the head pointer
}
static void Reverse(struct node** headRef) {
struct node* result = NULL;
struct node* current = *headRef;
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;
}
*headRef = result;
}
the recurse version is awkward because the problem in nature is not recursive. what is the point
Item* Reverse(Item* head)
{
if (!head || !head->next)
return head;
Item* last = head;
Item* newHead = head->next;
last->next = NULL;
while (newHead)
{
Item* temp = newHead;
newHead = newHead->next;
temp->next = last;
last = temp;
}
newHead = last;
return newHead;
}
Item* Reverse2(Item* head)
{
if (!head || !head->next)
return head;
Item* temp = head->next;
Item* newHead = Reverse2(head->next);
temp->next = head;
head->next = NULL;
return newHead;
}
PNode RecurReverseLink( PNode L )
{
if( L == NULL )
{
return L;
}
if( L->next == NULL )
{
return L;
}
PNode p = L->next;// tricky,p holds the tail of sub-link
PNode newHead = RecurReverseLink( L->next );
p->next = L;
L->next = NULL;
L = newHead;
return L;
}
public static reverse(LinkedlistNode head){
LinkedListNode before=null, current=head.next, next;
while(current!=null){
next=current.next;
current.next=before;
before=current;
current=next;
}
return before;
}
recursive approach :
- tom September 07, 2008struct node *reverse(struct node *p)
{
static struct node *headnode=NULL;
static struct node *reversehead=NULL;
struct node *q;
if(headnode == NULL)
{
headnode=p;
}
if(p->next == NULL)
return p;
}
q=p;
p=reverse(p->next);
if(reversehead == NULL)
{
reversehead = p;
}
p->next=q;
if(q == headnode)
{
q->next == NULL;
return reversehead;
}
retun q;
}
Pls give ur feedback .