-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack.c
51 lines (45 loc) · 1.18 KB
/
stack.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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "stack.h"
// Function to create a new stack
Stack *createStack() {
Stack *stack = (Stack *)malloc(sizeof(Stack));
if (stack == NULL) {
fprintf(stderr, "Memory allocation error\n");
}
stack->head = NULL;
return stack;
}
// Function to push a value onto the stack
void push(Stack *stack, char *val) {
StackNode *newNode = (StackNode *)malloc(sizeof(StackNode));
if (newNode == NULL) {
fprintf(stderr, "Memory allocation error\n");
}
newNode->value = strdup(val);
newNode->next = stack->head;
stack->head = newNode;
}
// Function to pop a value from the stack
char *pop(Stack *stack) {
if (isEmpty(stack)) {
fprintf(stderr, "Error: can't pop an empty stack'\n");
}
StackNode *temp = stack->head;
char *value = temp->value;
stack->head = temp->next;
free(temp);
return value;
}
// Function to check if the stack is empty
int isEmpty(Stack *stack) {
return stack->head == NULL;
}
// Function to free memory allocated to the stack
void destroyStack(Stack *stack) {
while (!isEmpty(stack)) {
pop(stack);
}
free(stack);
}