0% found this document useful (0 votes)
14 views3 pages

StackUsingLL Tilak Jain H2 42

The document contains a C program that implements a stack using a linked list. It provides functions to push, pop, peek, and display elements in the stack, along with a main menu for user interaction. The program handles memory allocation and checks for stack underflow and overflow conditions.

Uploaded by

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

StackUsingLL Tilak Jain H2 42

The document contains a C program that implements a stack using a linked list. It provides functions to push, pop, peek, and display elements in the stack, along with a main menu for user interaction. The program handles memory allocation and checks for stack underflow and overflow conditions.

Uploaded by

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

CODE :

#include <stdio.h>
#include <stdlib.h>

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

struct Node* top = NULL;

void push() {
int value;
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (!newNode) {
printf("Heap Overflow Cannot push more elements\n");
return;
}
printf("Enter the value to push ");
scanf("%d", &value);
newNode->data = value;
newNode->next = top;
top = newNode;
printf("%d pushed to stack\n", value);
}

void pop() {
if (top == NULL) {
printf("Stack Underflow Cannot pop from an empty stack\n");
} else {
struct Node* temp = top;
printf("%d popped from stack\n", temp->data);
top = top->next;
free(temp);
}
}

void peek() {
if (top == NULL) {
printf("Stack is empty\n");
} else {
printf("Top element %d\n", top->data);
}
}

void display() {
if (top == NULL) {
printf("Stack is empty\n");
} else {
struct Node* temp = top;
printf("Stack elements ");
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
}

int main() {
int choice;
while (1) {
printf("\n1 Push\n2 Pop\n3 Peek\n4 Display\n5 Exit\n");
printf("Enter your choice ");
scanf("%d", &choice);

switch (choice) {
case 1: push(); break;
case 2: pop(); break;
case 3: peek(); break;
case 4: display(); break;
case 5: printf("Exiting program\n"); return 0;
default: printf("Invalid choice Please try again\n");
}
}
}

OUTPUT:

You might also like