0% found this document useful (0 votes)
4 views4 pages

20

This document contains a C program that implements a stack using a linked list. It includes functions for checking if the stack is empty, displaying elements, pushing and popping elements, and showing the top element. A menu-driven interface allows users to interact with the stack through various options.

Uploaded by

rishoomishra0
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views4 pages

20

This document contains a C program that implements a stack using a linked list. It includes functions for checking if the stack is empty, displaying elements, pushing and popping elements, and showing the top element. A menu-driven interface allows users to interact with the stack through various options.

Uploaded by

rishoomishra0
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

#include <stdio.

h>

#include <stdlib.h>

struct Node {

int data;

struct Node* next;

};

struct Node* top = NULL;

int isEmpty() {

return top == NULL;

void display() {

if (isEmpty()) {

printf("Stack is empty.\n");

return;

struct Node* temp = top;

while (temp != NULL) {

printf("%d ", temp->data);

temp = temp->next;

printf("\n");

void push(int val) {

struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));


newNode->data = val;

newNode->next = top;

top = newNode;

int pop() {

if (isEmpty()) {

printf("Stack underflow.\n");

return -1;

struct Node* temp = top;

int val = temp->data;

top = top->next;

free(temp);

return val;

void topElement() {

if (isEmpty()) {

printf("Stack is empty.\n");

return;

printf("Top element: %d\n", top->data);

void menu() {

int choice, val;

while (1) {

printf("\nMenu:\n");
printf("1. Check if stack is empty\n");

printf("2. Display stack elements\n");

printf("3. Display top element\n");

printf("4. Push an element\n");

printf("5. Pop an element\n");

printf("6. Exit\n");

printf("Enter your choice: ");

scanf("%d", &choice);

switch (choice) {

case 1:

if (isEmpty()) printf("Stack is empty.\n");

else printf("Stack is not empty.\n");

break;

case 2:

display();

break;

case 3:

topElement();

break;

case 4:

printf("Enter value to push: ");

scanf("%d", &val);

push(val);

break;

case 5:

val = pop();

if (val != -1) printf("Popped value: %d\n", val);

break;

case 6:
exit(0);

default:

printf("Invalid choice.\n");

int main() {

menu();

return 0;

You might also like