Stack Using Linkedlist
Stack Using Linkedlist
#include<stdio.h>
#include<stdlib.h>
void push(int x);
void pop();
void display();
void count();
void peek();
void isempty();
void search();
struct stack
{
int data;
struct stack *next;
};
typedef struct stack stack;
stack *top = 0, *newnode, *temp;
int
main ()
{
int x, ch;
do
{
printf("1.push\n2.pop\n3.display\n4.count\n5.peek\n6.isempty\n7.search");
printf ("\n enter the choice::");
scanf ("%d", &ch);
switch (ch)
{
case 1:
printf ("\n enter the number::");
scanf ("%d", &x);
push (x);
break;
case 2:
pop ();
break;
case 3:
display ();
break;
case 4:
count ();
break;
case 5:
peek ();
break;
case 6:
isempty ();
break;
case 7:
search ();
break;
default:
printf ("\n ivalid choice!!");
break;
}
printf("\n do you want to continue(press 1)::");
scanf("%d",&ch);
}while(ch==1);
}
void push(int x)
{
newnode=(stack *)malloc(sizeof(stack));
if(newnode==NULL)
{
printf("\n memory is not allocate!!");
}
else
{
newnode->data=x;
newnode->next=top;
top=newnode;
}
}
void pop()
{
if(top==0)
{
printf("\n stack is empty");
}
else
{
temp=top;
printf("\n %d is deleted",top->data);
top=top->next;
free(temp);
}
}
void display()
{
if(top==0)
{
printf("\n stack is empty");
}
else
{
temp=top;
while(temp->next!=0)
{
printf("%d---->",temp->data);
temp=temp->next;
}
printf("%d",temp->data);
}
}
void count()
{
int c=0;
if(top==0)
{
printf("\n stack is empty");
}
else
{
temp=top;
while(temp->next!=0)
{
c++;
temp=temp->next;
}
c++;
printf("\ncount=%d",c);
}
}
void peek()
if(top==0)
{
printf("\n stack is empty");
}
else
{
printf("\n%d is the peek element",top->data);
}
}
void isempty()
{
if(top==0)
{
printf("\n stack is empty");
}
else
{
printf("\n stack is not empty");
}
}
void search()
{
int key,i=0,flag=0;
if(top==0)
{
printf("\n stack is empty");
}
else
{
temp=top;
printf("\n enter the number:");
scanf("%d",&key);
while(temp->next!=0)
{
i=i+1;
if(temp->data==key)
{
flag=1;
printf("\n element is found at %d place",i);
}
temp=temp->next;
}
if(temp->data==key)
{
i=i+1;
flag=1;
printf("\n element is found at %d place",i);
}
if(flag==0)
{
printf("\n elemeent is not found");
}
}
}