Wednesday, January 5, 2011

link list

#include<iostream.h>
#include<conio.h>
#include<alloc.h>
#include<stdio.h>
#include<dos.h>
#include<string.h>
#define INTERVAL 100

typedef struct node* link;
typedef int itemType;


struct node {
  itemType item;
  link next;
  };


typedef struct list {
link head, tail;
     };

//functions signatures.

  void initList(list*);
  link newNode(itemType);
  void insertFront(list*, link);
  void insertRear(list*, link);
  void insertNext(list*,itemType,link);
  void deleteNode(list*, itemType);
  void printList(list*);

  //main program which make use of list processing interface.

void main(){
  clrscr();
  list* l;
  link temp1,temp2;
  initList(l);
  temp1=newNode(12);
  insertFront(l,temp1);
   printList(l);

   temp2=newNode(20);
   insertRear(l,temp2);
   printList(l);
   temp2=newNode(30);
   insertRear(l,temp2);
   printList(l);
   temp2=newNode(50);
   insertRear(l,temp2);
   printList(l);
   temp2=newNode(45);
   insertNext(l,12,temp2);
   printList(l);

   deleteNode(l,45);
   printList(l);
   getch();


   // finalising....freeing used memory..
   delete l;
   clrscr();
   cout<<"Memory released....press any key...";
   getch();

}



// method list are implemented below.

void initList(list *l)
   {
l->head = l->tail=NULL;
    }

link newNode(itemType d)
   {
link temp;
itemType t;
temp =(link)malloc(sizeof(node));
//temp =(link)malloc(sizeof(link));
temp->item = d;
temp->next = NULL;
return temp;
   }

void insertFront(list *l, link t)
{
if (l->head==NULL)
{l->head = l->tail=t;}
else {
t->next = l->head;
l->head=t;
}
}

void insertRear(list* l, link t)
{
if (l->head==NULL)
l->head = l->tail= t;
else {
l->tail->next=t;
l->tail= t;
       }
}

void insertNext(list *l, itemType x, link t)
{
link temp;
int found=0;

if (l->head==NULL)
l->head = l->tail= t;
else{
temp=l->head;
while(temp !=NULL && (!found))
{
if (temp->item==x)
found =1;

else{
temp=temp->next;
found =0;
}
}
if(found)
{
t->next = temp->next;
temp->next=t;
}
else {
t->next=l->head;
l->head = t;
}
  }
}


void deleteNode(list* l, itemType d)
{
link temp1, temp2;
int found=0;
temp1 = l->head;
temp2 =temp1;

while((!found) && (temp1!= NULL))
{


if((temp1->item)==d){
found =1;
break;
}
else
{
temp2=temp1;
temp1=temp1->next;
}
}
if(found)
{
if(temp2 == temp1){
l->head=temp2->next;

}
else  {
temp2->next=temp1->next;

}
 delete temp1;
 cout<<"Succesfully deleted..."<<endl;
     }
else
cout<<"The node does not exists.."<<endl;
}

void printList(list *l)
{
link temp;
temp=l->head;
while(temp !=NULL)
{       delay(INTERVAL);
cout<< temp->item<<"\t"; /*display must be defined according to the itemType*/
temp=temp->next;
}
cout<<endl;
}

No comments:

Post a Comment