mockers
Would you like to react to this message? Create an account in a few clicks or log in to continue.

Linked List

2 posters

mockers :: DS

Go down

Linked List Empty Linked List

Post  ramthegreatcv Mon May 25, 2009 5:16 pm

remember no company asks coding of graphs.however linked list,stacks,queues etc are frequently asked.
ALL THE BEST
ramthegreatcv
ramthegreatcv

Posts : 55
Join date : 2009-01-30
Age : 36

Back to top Go down

Linked List Empty Reverse Algo (both Recursive,Iterative)

Post  Admin Tue Jun 23, 2009 6:50 pm

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

Admin
Admin

Posts : 47
Join date : 2009-01-29

https://mockers.forumotion.com

Back to top Go down

Back to top

- Similar topics

mockers :: DS

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