Zynga Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: In-Person
Iterative Approach:
let the pointer 'second' points to first node , the pointer 'first' points to second node and the pointer 'third' points to null.
while(second!=null)
{
second -> next = third;
first -> next = second;
third = second;
second = first;
first = first -> next;
}
A recursive approach:
rev(root)
{
if(!root || !(root->next))
newroot=root;
else
{
rev(root->next);
if(root->next)
{
root->next->next=root;
root->next=NULL;
}
}
return newroot;
}
An iterative one:
iterativerev(root)
{
Node *p,*q,*r;
q=root;
while(q)
{
r=q->next;
q->next=p;
p=q;
q=r;
}
return p;
}
/////////// iterative
LinkNode *reverseLink(LinkNode *head)
{
if(head == NULL)
return NULL;
if(head->next == NULL)
return head;
if(head->next->next == NULL)
{
LinkNode *tail = head->next;
head->next->next = head;
head->next = NULL;
return tail;
}
LinkNode *pre = head;
LinkNode *current = head->next;
LinkNode *next = head->next->next;
while(next != NULL)
{
current->next = pre;
pre = current;
current = next;
next = next->next;
}
head->next = NULL;
current->next = pre;
return current;
}
////////////recursive
LinkNode *reverseLink(LinkNode *head)
{
if(head == NULL)
return NULL;
if(head->next == NULL)
return head;
LinkNode *next = reverseLink(head->next);
next->next = head;
head->next = NULL;
return head;
}
- mykola July 08, 2012