Reverse a list
4 posters
Page 1 of 1
Reverse a list
write a code to reverse a singly linked list....
If done with this try it for a Doubly linked list.
If done with this try it for a Doubly linked list.
Pulkit- Posts : 2
Join date : 2008-08-10
Re: Reverse a list
node *p,*head,*q,*r;
p=head;
q=NULL;
while(p!=NULL)
{r=p->next;
p->next=q;
q=p;
p=r;
}
head=q;
p=head;
q=NULL;
while(p!=NULL)
{r=p->next;
p->next=q;
q=p;
p=r;
}
head=q;
sweetesh singh- Posts : 8
Join date : 2008-08-12
recursive version
struct node* reverser(struct node *p){
if(p->link){
reverser(p->link)->link=p;
p->link=NULL;
}
else
head=p;
return p;
}
if(p->link){
reverser(p->link)->link=p;
p->link=NULL;
}
else
head=p;
return p;
}
ankurgutpa- Posts : 44
Join date : 2008-08-10
Age : 36
Location : Tandon 72
Re: Reverse a list
similarly for DLL
struct node* reverser(struct node *p){
struct node *temp;
if(p->next){
temp=reverser(p->next);
temp->next=p;
p->prev=temp;
p->next=NULL;
}
else{
head=p;
p->prev=NULL;
}
return p;
}
i would like to know if an algo exist(recursive version) which return head of LL and DLL to the calling function
struct node* reverser(struct node *p){
struct node *temp;
if(p->next){
temp=reverser(p->next);
temp->next=p;
p->prev=temp;
p->next=NULL;
}
else{
head=p;
p->prev=NULL;
}
return p;
}
i would like to know if an algo exist(recursive version) which return head of LL and DLL to the calling function
ankurgutpa- Posts : 44
Join date : 2008-08-10
Age : 36
Location : Tandon 72
reversing singly link list
void reverse()
{
int stack[10];
int top=-1;
node *tmp,*tmp1,*front=NULL;
tmp=start;
while(start!=NULL)
{
stack[++top]=start->n;
start=start->next;
}
stack[++top]=start->n;
while(top>=0)
{
if(front==NULL)
{
tmp=(node*)malloc(sizeof(node*));
tmp->n=stack[top--];
tmp->next=NULL;
front=tmp;
tmp1=front;
}
else
{
tmp=(node*)malloc(sizeof(node*));
tmp->n=stack[top--];
tmp->next=NULL;
tmp1->next=tmp;
tmp1=tmp1->next;
}
}
if(front==NULL)
{
cout<<"list is empty\n";
return;
}
tmp=front;
while(tmp!=NULL)
{
cout<<tmp->n<<endl;
tmp=tmp->next;
}
cout<<tmp->n;
}
{
int stack[10];
int top=-1;
node *tmp,*tmp1,*front=NULL;
tmp=start;
while(start!=NULL)
{
stack[++top]=start->n;
start=start->next;
}
stack[++top]=start->n;
while(top>=0)
{
if(front==NULL)
{
tmp=(node*)malloc(sizeof(node*));
tmp->n=stack[top--];
tmp->next=NULL;
front=tmp;
tmp1=front;
}
else
{
tmp=(node*)malloc(sizeof(node*));
tmp->n=stack[top--];
tmp->next=NULL;
tmp1->next=tmp;
tmp1=tmp1->next;
}
}
if(front==NULL)
{
cout<<"list is empty\n";
return;
}
tmp=front;
while(tmp!=NULL)
{
cout<<tmp->n<<endl;
tmp=tmp->next;
}
cout<<tmp->n;
}
harit- Posts : 2
Join date : 2008-09-09
Page 1 of 1
Permissions in this forum:
You cannot reply to topics in this forum