-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStacks.c
68 lines (55 loc) · 1.33 KB
/
Stacks.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
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 10
// Define the structure for a stack
typedef struct {
int items[MAX_SIZE];
int top;
} Stack;
// Function to initialize a stack
void initializeStack(Stack *s) {
s->top = -1;
}
// Function to check if the stack is full
int isFull(Stack *s) {
return s->top == MAX_SIZE - 1;
}
// Function to check if the stack is empty
int isEmpty(Stack *s) {
return s->top == -1;
}
// Function to push an item onto the stack
void push(Stack *s, int item) {
if (isFull(s)) {
printf("Stack is full. Cannot push %d.\n", item);
return;
}
s->items[++s->top] = item;
}
// Function to pop an item from the stack
int pop(Stack *s) {
if (isEmpty(s)) {
printf("Stack is empty. Cannot pop.\n");
return -1; // Assuming -1 indicates an error
}
return s->items[s->top--];
}
// Function to peek at the top of the stack
int peek(Stack *s) {
if (isEmpty(s)) {
printf("Stack is empty.\n");
return -1; // Assuming -1 indicates an error
}
return s->items[s->top];
}
int main() {
Stack s;
initializeStack(&s);
push(&s, 5);
push(&s, 10);
push(&s, 15);
printf("Top of stack: %d\n", peek(&s));
printf("Popped: %d\n", pop(&s));
printf("Top of stack after pop: %d\n", peek(&s));
return 0;
}