Adobe Interview Question
Software Engineer / DevelopersCountry: India
Interview Type: Written Test
//Write a function for reversing a doubly linked list.
#include<stdio.h>
struct node *head;
struct node
{
int val;
struct node *next;
struct node *prev;
};
void insert(int x, struct node *head)
{
struct node *p;
struct node *t = (struct node*) malloc (sizeof(struct node));
t->val = x;
t->next = t->prev = NULL;
p = head;
while(p->next != NULL)
{
p = p->next;
}
t->prev = p;
p->next = t;
}
void reverse(struct node *head)
{
struct node *p,*temp;
p = head;
while(p != NULL)
{
temp = p->prev;
p->prev = p->next;
p->next = temp;
p = p->prev;
}
head = temp->prev;
printf("\nReversed Values in the linked list are :\n");
p = head;
while(p != NULL)
{
printf("%d\t",p->val);
p = p->next;
}
}
void display(struct node *head)
{
struct node *p;
p = head;
while(p != NULL)
{
printf("%d\t",p->val);
p = p->next;
}
}
int main()
{
head = (struct node*) malloc (sizeof(struct node));
head->next = head->prev = NULL;
head->val = 4;
insert(5,head);
insert(6,head);
insert(7,head);
printf("\nValues in the linked list are :\n");
display(head);
reverse(head);
}
#include<stdio.h>
#include<malloc.h>
struct node
{
int data;
struct node *prev;
struct node * next;
};
void append(struct node **,int);
void display(struct node *);
void reverse( struct node **);
int main()
{
struct node *p;
p=NULL;
append(&p,21);
append(&p,31);
append(&p,41);
append(&p,51);
append(&p,61);
display(p);
reverse(&p);
display(p);
return 0;
}
void append(struct node **q, int num)
{
struct node *temp,*r;
if (*q==NULL)
{
temp=(struct node *)malloc(sizeof(struct node*));
temp->data=num;
temp->prev=NULL;
temp->next=NULL;
*q=temp;
}
else
{
temp=*q;
while(temp->next!=NULL)
temp=temp->next;
r=(struct node *)malloc(sizeof(struct node *));
r->data=num;
temp->next=r;
r->next=NULL;
r->prev=temp;
}
}
void display(struct node *q)
{
while(q!=NULL)
{
printf("%d \t",q->data);
q=q->next;
}
printf("\n");
}
void reverse(struct node **q)
{
struct node *temp,*current;
current=*q;
temp=NULL;
while(current!=NULL)
{
current->prev=current->next;
current->next=temp;
temp=current;
current=current->prev;
}
*q=temp;
}
simple, just to traverse through the list and swap next, prev pointer for each item.
- Anonymous April 16, 2012