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

Ds 12

Uploaded by

anavadyapradeep
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)
8 views3 pages

Ds 12

Uploaded by

anavadyapradeep
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

Program

/* Experiment No.12 Stack using Linked List


Write a menu driven Program to implement a stack using linked list
with the following operations:
a.Push an element to the stack
b.Pop an element from the stack
c.Display the content of the stack
17.Anavadya Pradeep.23/09/2024 */
#include <stdio.h>
#include <stdlib.h>
// Define the structure for a node
typedef struct Node {
int data;
struct Node* next;
} Node;
// Define the structure for the stack
typedef struct {
Node* top;
} Stack;
// Function to create a new node
Node* createNode(int data) {
Node* newNode = (Node*) malloc(sizeof(Node));
if (!newNode) {
printf("Memory error\n");
return NULL;
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// Function to create a new stack
Stack* createStack() {
Stack* stack = (Stack*) malloc(sizeof(Stack));
if (!stack) {
printf("Memory error\n");
return NULL;
}
stack->top = NULL;
return stack;
}
// Function to check if the stack is empty
int isEmpty(Stack* stack) {
return stack->top == NULL;
}
// Function to push an element onto the stack
void push(Stack* stack, int data) {
Node* newNode = createNode(data);
if (isEmpty(stack)) {
stack->top = newNode;
}
else {
newNode->next = stack->top;
stack->top = newNode;
}
printf("%d pushed to stack\n", data);
}
// Function to pop an element from the stack
void pop(Stack* stack) {
if (isEmpty(stack)) {
printf("Stack is empty\n");
}
else {
Node* temp = stack->top;
printf("%d popped from stack\n", temp->data);
stack->top = temp->next;
free(temp);
}
}
// Function to display the stack
void display(Stack* stack) {
Node* temp = stack->top;
if (isEmpty(stack)) {
printf("Stack is empty\n");
}
else {
printf("Stack elements: ");
while (temp) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
}
// Main function
int main() {
Stack* stack = createStack();
int choice, data;
printf("Stack Operations\n");
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Display\n");
printf("4. Exit\n");
do{
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter data to push: ");
scanf("%d", &data);
push(stack, data);
break;

case 2:
pop(stack);
break;

case 3:
display(stack);
break;

case 4:
return 0;

default:
printf("Invalid choice\n");
}
} while(choice!=4);
}
Sample Output

Result
The program was executed and the output verified.

You might also like