-
Notifications
You must be signed in to change notification settings - Fork 0
/
stackLinkedList.c
127 lines (106 loc) · 3.04 KB
/
stackLinkedList.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#include <stdio.h>
#include <stdlib.h>
// Node structure for the linked list
struct Node {
int data;
struct Node* next;
};
// Stack structure
struct Stack {
struct Node* top;
};
// Function to initialize the stack
void initializeStack(struct Stack* stack) {
stack->top = NULL;
}
// Function to check if the stack is empty
int isEmpty(struct Stack* stack) {
return (stack->top == NULL);
}
// Function to push an element onto the stack
void push(struct Stack* stack, int data) {
// Create a new node
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Memory allocation failed. Cannot push %d\n", data);
return;
}
// Set the data and next pointer
newNode->data = data;
newNode->next = stack->top;
// Update the top pointer
stack->top = newNode;
printf("%d pushed onto the stack\n", data);
}
// Function to pop an element from the stack
int pop(struct Stack* stack) {
if (isEmpty(stack)) {
printf("Stack Underflow. Cannot pop\n");
return -1;
}
// Get the data from the top node
int data = stack->top->data;
// Update the top pointer and free the top node
struct Node* temp = stack->top;
stack->top = stack->top->next;
free(temp);
printf("%d popped from the stack\n", data);
return data;
}
// Function to display the elements of the stack
void displayStack(struct Stack* stack) {
if (isEmpty(stack)) {
printf("Stack is empty\n");
return;
}
printf("Elements in the stack: ");
struct Node* current = stack->top;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
// Function to free the memory used by the stack
void freeStack(struct Stack* stack) {
while (stack->top != NULL) {
struct Node* temp = stack->top;
stack->top = stack->top->next;
free(temp);
}
}
int main() {
struct Stack stack;
initializeStack(&stack);
int choice, data;
do {
printf("\n----- Stack Menu -----\n");
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Display\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter the element to push: ");
scanf("%d", &data);
push(&stack, data);
break;
case 2:
pop(&stack);
break;
case 3:
displayStack(&stack);
break;
case 4:
printf("Exiting the program\n");
break;
default:
printf("Invalid choice. Please enter a valid option.\n");
}
} while (choice != 4);
// Free the memory used by the stack before exiting
freeStack(&stack);
return 0;
}