Amazon Interview Question
Software Engineer / DevelopersDo we need to reverse the Doubly Linked list? I can simply change the Head to the last node.
As it is double linked, its done I think.
Please correct me if I am missing something.
reverse(Node** head){
Node* node = *head;
Node* temp = NULL;
while(node != NULL){
temp = node->prev;
node->prev = node->next;
node->next = temp;
node = node->prev;
}
if(temp != NULL)
*head = temp->prev;
}
#include<iostream>
using namespace std;
class node {
int data;
node *next;
node *prev;
public:
node()
{
data=0;
next=prev=NULL;
}
friend class ll;
};
class ll {
node *start;
public:
ll()
{
start=NULL;
}
void insert()
{
int num;
do {
cout<<"entr num 2 b inserted\n";
cin>>num;
if(num!=-1)
{
node *temp=new node;
temp->data=num;
temp->next=temp->prev=NULL;
if(start==NULL)
{
start=temp;
}
else
{
node *t=start;
while(t->next!=NULL)
t=t->next;
t->next=temp;
temp->prev=t;
temp->next=NULL;
}
}
else ;
}while(num!=-1);
}
void display()
{
node *t=start;
while(t)
{
cout<<t->data<<" ";
t=t->next;
}
cout<<endl;
}
void rev()
{
node *xx=NULL;
node *curr=start;
node *temp=NULL;
while(curr!=NULL)
{
temp=curr->next;
curr->next=xx;
curr->prev=temp;
xx=curr;
curr=temp;
}
start=xx;
}
};
int main()
{
ll l;
l.insert();
l.display();
l.rev();
l.display();
return 0;
}
<pre lang="" line="1" title="CodeMonkey76510" class="run-this"> public LLNode Reverse(LLNode node)
{
if (node == null || node.Next == null)
return node;
LLNode head = node, tmpNode = node;
while (tmpNode!=null)
{
tmpNode = head.Next.Next;
head.Next = head;
if (tmpNode != null)
head = tmpNode;
}
node.Next = null;
return head;
}</pre><pre title="CodeMonkey76510" input="yes">
</pre>
there are 3 ways :
1. create a new doubly linked list and copy the values with reversing the prev and next pointers
2. swap values of last with first, second-last with second and so on
3. change the head from first to last node and reverse the prev next.
Logically it does not make much difference except the head but when asked for reversing we shud consider the pointers next and prev