Thursday, August 26, 2010

LinkLists in C++: Part 1



First in the series of Link-List funtions.

/***************************************************/
#include< iostream.h >
#include< conio.h >
#include< stdlib.h >

struct node
{
int info;
node* next;
}*start, *end, *t;

void addnode()
{
int ch;
if(start == NULL)
{
start = new node;
if(start == NULL)
{
cout <<"\nNOT ENOUGH MEMORY";
getch();
exit(0);
}
cout <<"\nENTER INFO";
cin >>start->info;
start->next = NULL;
end = start;
}
else
{
cout <<"\n1.ADD IN THE BEGINNING.";
cout <<"\n2.ADD AT THE END.";
cout <<"\n3.ADD IN THE MIDDLE.";
cout <<"\n4.EXIT.";
cout <<"\n\nENTER CHOICE ::";
cin >> ch;
switch(ch)
{
case 1:addbeg();
break;
case 2:addend();
break;
case 3:addmid();
break;
case 4:exit(0);
break;
default:cout <<"WRONG CHOICE.";
}
}
}

void addbeg()
{
t = new node;
if(t == NULL)
{
cout <<"\nNOT ENOUGH MEMORY";
getch();
exit(0);
}
cout <<"\nENTER INFO :: ";
cin >>t->info;
t->next = start;
start = t;
}

void addend()
{
t = new node;
if(t == NULL)
{
cout <<"\nNOT ENOUGH MEMORY";
getch();
exit(0);
}
cout <<"\nENTER INFO :: ";
cin >>t->info;
t->next = NULL;
end->next = t;
end = t;

}

void addmid()
{
int ch;
cout <<"\n1.ADD BEFORE A GIVEN NODE.";
cout <<"\n2.ADD AFTER A GIVEN NODE.";
cout <<"\nENTER CHOICE :: ";
cin >> ch;
switch(ch)
{
case 1:addbefore();
break;
case 2:addafter();
break;
default:cout <<"\nWRONG CHOICE";
}
}

void addbefore()
{
int n;
cout <<"\nENTER THE NODE INFO.";
cin >>n;
t = start;
while(t != NULL)
{
if(t->next->info == n)
{
t1 = new node;
if(t1 == NULL)
{
cout<<"\nNOT ENOUGH MEMORY";
getch();
exit(0);
}
cout <<"\nENTER INFO";
cin >>t1->info;
t1->next = t->next;
t->next = t1;
}
t = t->next;
}
}

void addafter()
{
int n;
cout <<"\nENTER THE NODE INFO.";
cin >>n;
t = start;
while(t != NULL)
{
if(t->info == n)
{
t1 = new node;
if(t1 == NULL)
{
cout<<"\nNOT ENOUGH MEMORY";
getch();
exit(0);
}
cout <<"\nENTER INFO";
cin >>t1->info;
t1->next = t->next;
t->next = t1;
}
t = t->next;
}
}

No comments:

Post a Comment