Professional Documents
Culture Documents
Stack Using SLL
Stack Using SLL
h>
#include<stdlib.h>
struct node {
int data;
struct node *link;
};
int isEmpty()
{
if (top == NULL){
return 1;
}
else
{
return 0;
}
}
temp->data = ele;
temp->link = top;
top = temp;
}
int pop(){
if ( isEmpty()){
printf("Stack is empty");
}
else
{
struct node *temp;
int ele;
temp = top;
top = temp->link;
temp->link = NULL;
ele = temp->data;
free(temp);
return ele;
}
return 0;
void traverse(){
if ( isEmpty()){
printf("Stack is empty");
}
else
{
struct node *temp = top;
printf("Elements of the stack are : \n");
while(temp != NULL){
printf("%d ",temp->data);
temp = temp->link;
}
}
}
int peek(){
if (isEmpty()){
printf("Stack is empty ");
return 0;
}
else
{
return top->data;
}
int length(){
if (isEmpty()){
return 0;
}
else{
struct node *temp = top;
int count = 0;
while(temp != NULL){
count ++;
temp = temp->link;
}
return count;
}
}
int main(){
while (1)
{
printf("\nEnter \n 1.push \n 2.pop \n 3.traverse \n 4.peek \n 5.length \n
6.exit \n");
printf("Enter your choice : ");
scanf("%d", &choice);
switch (choice)
{
case 1:
printf("Enter element to insert : ");
scanf("%d", &ele);
push(ele);
break;
case 2:
printf("%d deleted ",pop());
break;
case 3:
traverse();
break;
case 4:
printf("Top element of the stack is : %d",peek() );
break;
case 5:
printf("Length of the stack is : %d", length());
break;
case 6:
exit(0);
}
}
return 0;
}