Tuesday, October 7, 2008

Stack using Linked List

/* Implementation of stack using linked list */

#include
#include

void push();
void pop();
void view();

struct node
{
int data;
struct node *next;
};

struct node *top=NULL;

main()
{

int n;

do
{
printf("\n\n\n\n"
"1.push an element\n"
"2.pop an element\n"
"3.view and count\n"
"4.end the program\n"
"\nenter your choice number : ");
scanf("%d",&n);

switch(n)
{
case 1:
push();
break;

case 2:
pop();
break;

case 3:
view();
break;

case 4:
printf("\n\t---------------THANKS FOR USING-------------\n\n"); break;

default:
printf("\n\nenter the choice 1 to 3 only : ");
scanf("%d",&n);

}

} while(n<4);

}


void push()
{
struct node *temp;
temp=(struct node*) malloc (sizeof(struct node));

int v;
if(temp==NULL)
{
printf("\nthe stack is over flow\n\n");

}

else
{
printf("\n\nenter the element : ");
scanf("%d",&v);

temp->data=v;
temp->next=top;
top=temp;

}

return;
}


void pop()
{
int v;

if(top==NULL)
{
printf("the stack is underflow");
}
else
{
v=top->data;
printf("\nthe poped element is %d \n\n",top->data);
top=top->next;
}
return;
}



void view()
{

struct node *temp1;
int count=0;
temp1=top;
if(temp1==NULL)
{
printf("the stack is empty");
}

else
{

printf("\nthe elements in the stack are :\n");
for(;temp1!=NULL;temp1=temp1->next)
{
printf("\t\t\t\t%d\n",temp1->data);
count=count+1;

}
}

printf("\nthe number of elements in the stack is -> %d\n\n",count);

return;

}

No comments: