Reverse a list

Go down

Reverse a list

Post  Pulkit on Tue Aug 12, 2008 11:08 am

write a code to reverse a singly linked list....

If done with this try it for a Doubly linked list.

Pulkit

Posts : 2
Join date : 2008-08-10

View user profile

Back to top Go down

Re: Reverse a list

Post  sweetesh singh on Tue Aug 12, 2008 11:28 am

node *p,*head,*q,*r;
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

View user profile

Back to top Go down

recursive version

Post  ankurgutpa on Tue Aug 12, 2008 11:45 am

struct node* reverser(struct node *p){
if(p->link){
reverser(p->link)->link=p;
p->link=NULL;
}
else
head=p;
return p;
} cheers
avatar
ankurgutpa

Posts : 44
Join date : 2008-08-10
Age : 30
Location : Tandon 72

View user profile

Back to top Go down

Re: Reverse a list

Post  ankurgutpa on Tue Aug 12, 2008 4:21 pm

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 cheers
avatar
ankurgutpa

Posts : 44
Join date : 2008-08-10
Age : 30
Location : Tandon 72

View user profile

Back to top Go down

reversing singly link list

Post  harit on Sat Sep 13, 2008 1:39 pm

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;
}

harit

Posts : 2
Join date : 2008-09-09

View user profile

Back to top Go down

Re: Reverse a list

Post  Sponsored content


Sponsored content


Back to top Go down

Back to top

- Similar topics

 
Permissions in this forum:
You cannot reply to topics in this forum