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

Stack Dynamic

The document contains a C program that implements a stack using a linked list. It includes functions to push, pop, and display elements in the stack, along with a user interface for interaction. The program demonstrates basic stack operations with example outputs for user choices.

Uploaded by

nikita.rathod
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)
6 views3 pages

Stack Dynamic

The document contains a C program that implements a stack using a linked list. It includes functions to push, pop, and display elements in the stack, along with a user interface for interaction. The program demonstrates basic stack operations with example outputs for user choices.

Uploaded by

nikita.rathod
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

Name : Nikita Rathod

Roll no :UEC2023252

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

// Define the structure for the stack node


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

// Push an element onto the stack


void push(struct Node** top, int value) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));

new_node->data = value;
new_node->next = *top;
*top = new_node;
printf("%d pushed to stack\n", value);
}

// Pop an element from the stack


int pop(struct Node** top) {
if (top==0) { printf("Stack is empty\n"); return -1; }
struct Node* temp = *top;
int popped_value = temp->data;
*top = temp->next;
free(temp);
return popped_value;
}

// Display the stack


void display(struct Node* top) {
if (top==0) { printf("Stack is empty\n"); return; }
printf("Stack: ");
for (struct Node* temp = top; temp; temp = temp->next)

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


printf("\n");
}

int main() {
struct Node* top = NULL;
int choice, value;

while (1) {
printf("\n1. Push\n2. Pop\n3. Display\n4. Exit\nChoice: ");
scanf("%d", &choice);
switch (choice) {
case 1: printf("Enter value to push: ");
scanf("%d", &value);
push(&top, value);
break;
case 2: value = pop(&top);

printf("Popped: %d\n", value);


break;
case 3: display(top);
break;
case 4: exit(0);
break;
default: printf("Invalid choice\n");
}
}

return 0;
}

output :

1. Push
2. Pop
3. Display
4. Exit
Choice: 1
Enter value to push: 10
10 pushed to stack

1. Push
2. Pop
3. Display
4. Exit
Choice: 1
Enter value to push: 20
20 pushed to stack

1. Push
2. Pop
3. Display
4. Exit
Choice: 1
Enter value to push: 30
30 pushed to stack

1. Push
2. Pop
3. Display
4. Exit
Choice: 3
Stack: 30 20 10

1. Push
2. Pop
3. Display
4. Exit
Choice: 2
Popped: 30

1. Push
2. Pop
3. Display
4. Exit
Choice: 3
Stack: 20 10

1. Push
2. Pop
3. Display
4. Exit
Choice: 4

You might also like