Linked List
2 posters
Linked List
remember no company asks coding of graphs.however linked list,stacks,queues etc are frequently asked.
ALL THE BEST
ALL THE BEST
ramthegreatcv- Posts : 55
Join date : 2009-01-30
Age : 36
Reverse Algo (both Recursive,Iterative)
a simple program that does basic operation of reverse on linked list.
- Code:
#include<iostream>
using namespace std;
struct node{
int data;
node *next;
node *prev;
};
node* add(node** top,int data){
node* temp = new node;
temp -> data = data;
temp -> next = *top;
return ((*top) = temp);
}
void print(node* top){
int c=0;
while(top != NULL){
cout<<top->data;
top = top->next;
c++ ;
if(c>5)
break;
}
}
/*
node* reverseRec(node*& p)
{
node* temp = NULL;
if(p->next == NULL)
return p;
temp = reverseRec(p->next);
temp->next = p;
return p;
}
*/
node* reverseItr(node* front)
{
node *p=NULL,*q=NULL,*r=NULL;
p = front;
if(p!=NULL)
{
q = p->next;
p->next = NULL;
}
if(q!=NULL)
r = q->next;
while(q!=NULL){
q->next = p;
p = q;
q = r;
if(r!=NULL)
r = r->next;
}
return p;
}
node* reverseRec(node* current, node* parent=NULL)
{
node* revhead = NULL;
if(current == NULL)
revhead = parent;
else{
revhead = reverseRec(current->next, current);
current->next = parent;
}
return revhead;
}
int main(){
node *front=NULL,*back=NULL;
//1->2->3->4;
back = add(&front,4);
add(&front,3);
add(&front,2);
add(&front,1);
cout<<" original : \t";
print(front);
cout<<"\n reversed: \t";
front = reverseRec(front);
print(front);
front = reverseItr(front);
cout<<"\n reversed again:";
print(front);
cout<<endl;
}
Similar topics
» Binary tree to Linked List
» Sorting Algorithms
» Best Method to sort Linked List?
» Questions asked in mocks
» List vs arrays:Vinisha Ma'am
» Sorting Algorithms
» Best Method to sort Linked List?
» Questions asked in mocks
» List vs arrays:Vinisha Ma'am
Permissions in this forum:
You cannot reply to topics in this forum
|
|