......................

Doubly Linked LIst

Posted by Unknown On Saturday, July 10, 2010 0 comments

#include "iostream.h"
#include "conio.h"

struct node
{
 int info;
 struct node *rptr,*lptr;
}*New,*head = NULL;

void create(int ITEM)
{
 New = new node;
 New -> info = ITEM;
 New -> lptr = NULL;
 New -> rptr = NULL;
 if(head == NULL)
  head = New;
}

void insert(int ITEM,int loc)
{
 create(ITEM);
 struct node *locPtr,*temp;
 if(loc <= 0)
  {
    cout << "Invalid Location";
    getch();
    return;
   }

 if(loc == 1)
  {
    New -> rptr = head;
    head -> lptr = New;
    head = New;
   }

 else
  {
    locPtr = head;
    for(int i = 2;i < loc;i++)
     {
       locPtr = locPtr -> rptr;
       if(locPtr == NULL)
       {
          cout << "Invalid Location";
          getch();
          return;
         }
       }

      temp = locPtr -> rptr;
      locPtr -> rptr = New;
      New -> lptr = locPtr;
      New -> rptr = temp;
      temp -> lptr = New;
   }
}

void remove(int loc)
{
 struct node *locPtr = head,*temp;
 if(loc <= 0)
  {
    cout << "Invalid Location.";
    getch();
    return;
   }

 if(loc == 1)
  {
    head = head -> rptr;
    delete head;
   }

 else
  {
   for(int i = 2;i < loc;i++)
   {
       locPtr = locPtr -> rptr;
       if(locPtr == NULL)
       {
          cout << "Invalid Location";
          getch();
          return;
         }
       }

   temp = locPtr -> rptr;
   locPtr -> rptr = temp -> rptr;
   delete temp;
   temp = temp -> rptr;
   temp -> lptr = locPtr;
  }
}

void display()
{
 struct node *temp = head;
 cout << temp -> info << ' ';
 while(temp -> rptr != NULL)
  {
    temp = temp -> rptr;
    cout << temp -> info << ' ';
   }
}

void displayBack()
{
 struct node *temp = head;
 while(temp -> rptr != NULL)
    temp = temp -> rptr;

 cout << temp -> info << ' ';
 while(temp -> lptr != NULL)
  {
    temp = temp -> lptr;
    cout << temp -> info << ' ';
   }
}

int main()
{
 create(0);
 for(int i = 1;i <= 5;i++)
  insert(6*i,i);

 display();
 cout << endl;
 displayBack();
 remove(3);
 cout << endl << endl;
 display();
 getch();
 return 0;
}

No comments:

Post a Comment

Leave Feedback about this BLOG