Stack
Stack
#include <stdio.h>
#define SIZE 10
int top = -1, arr[SIZE];
void push();
void pop();
void peep();
void display();
int main()
{
int choice;
printf("Operations of Stack:\n");
printf("1.Push\n2.Pop\n3.Peep\n4.Display\n5.Exit\n");
while(1)
{
printf("\nEnter your choice: ");
scanf("%d", &choice);
switch(choice)
{
case 1: push(); break;
case 2: pop(); break;
case 3: peep(); break;
case 4: display(); break;
case 5: return 0;
default: printf("\nInvalid choice, try again.\n");
}
}
}
void push()
{
int n;
if(top == SIZE - 1)
{
printf("\nStack overflow\n");
}
else
{
printf("Enter the element to be added onto the stack: ");
scanf("%d", &n);
top = top + 1;
arr[top] = n;
}
}
void pop()
{
if(top == -1) //w.s.enmpty
{
printf("\nStack underflow\n");
}
else
{
printf("Popped element: %d\n", arr[top]);
top = top - 1;
}
}
void peep()
{
if(top == -1)
{
printf("\nStack is empty, nothing to peep.\n");
}
else
{
printf("Top element of the stack: %d\n", arr[top]);
}
}
void display()
{
int i;
if(top == -1)
{
printf("\nStack is empty (underflow)\n");
}
else
{
printf("\nElements present in the stack:\n");
for(i = top; i >= 0; i--)
{
printf("%d\t", arr[i]);
}
}
}
Stack implementation using linked list.
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node* next;
};
struct Node* top = NULL;
int main()
{
int choice, item;
printf("Operations of Stack:\n");
printf("1. Push\n2. Pop\n3. Display\n4. Peep\n5. Exit\n");
while (1)
{
printf("\nEnter your choice: ");
scanf("%d", &choice);
switch(choice)
{
case 1: printf("Enter the item to push: ");
scanf("%d", &item);
push(item); break;
case 2: pop(); break;
case 3: peep(); break;
case 4: display(); break;
case 5: return 0;
default: printf("Invalid choice.\n");
}
}
}
void pop()
{
if (top == NULL) // Check if the stack is empty
{
printf("\nStack underflow\n");
}
else
{
struct Node* temp = top;
printf("Popped item: %d\n", temp->data);
top = top->next; // Move the top pointer to the next node
free(temp); // Free the memory of the popped node
}
}
void peep()
{
if (top == NULL)
{
printf("\nStack is empty, nothing to peep.\n");
}
else
{
printf("Top item: %d\n", top->data);
}
}
void display()
{
if (top == NULL) // Check if the stack is empty
{
printf("\nStack is empty (underflow)\n");
}
else
{
struct Node* temp = top;
printf("\nElements present in the stack:\n");
while (temp != NULL)
{
printf("%d\t", temp->data);
temp = temp->next;
}
printf("\n");
}
}