File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ #include <stdio.h>
2+ #include <stdlib.h>
3+
4+ #define MAX 100 // Maximum size of the stack
5+
6+ typedef struct Stack {
7+ int items [MAX ];
8+ int top ;
9+ } Stack ;
10+
11+ // Initialize the stack
12+ void initStack (Stack * s ) {
13+ s -> top = -1 ;
14+ }
15+
16+ // Check if the stack is empty
17+ int isEmpty (Stack * s ) {
18+ return s -> top == -1 ;
19+ }
20+
21+ // Check if the stack is full
22+ int isFull (Stack * s ) {
23+ return s -> top == MAX - 1 ;
24+ }
25+
26+ // Push an element onto the stack
27+ void push (Stack * s , int value ) {
28+ if (isFull (s )) {
29+ printf ("Stack Overflow!\n" );
30+ return ;
31+ }
32+ s -> items [++ (s -> top )] = value ;
33+ }
34+
35+ // Pop an element from the stack
36+ int pop (Stack * s ) {
37+ if (isEmpty (s )) {
38+ printf ("Stack Underflow!\n" );
39+ return -1 ;
40+ }
41+ return s -> items [(s -> top )-- ];
42+ }
43+
44+ // Peek the top element
45+ int peek (Stack * s ) {
46+ if (isEmpty (s )) {
47+ printf ("Stack is empty!\n" );
48+ return -1 ;
49+ }
50+ return s -> items [s -> top ];
51+ }
52+
53+ int main () {
54+ Stack stack ;
55+ initStack (& stack );
56+
57+ push (& stack , 10 );
58+ push (& stack , 20 );
59+ push (& stack , 30 );
60+
61+ printf ("Top element: %d\n" , peek (& stack ));
62+
63+ printf ("Popped: %d\n" , pop (& stack ));
64+ printf ("Popped: %d\n" , pop (& stack ));
65+
66+ if (isEmpty (& stack ))
67+ printf ("Stack is empty now.\n" );
68+
69+ return 0 ;
70+ }
You can’t perform that action at this time.
0 commit comments