Repository navigation
Expand file tree
/
Copy pathstack.c
More file actions
115 lines (102 loc) · 1.79 KB
/
Copy pathstack.c
File metadata and controls
115 lines (102 loc) · 1.79 KB
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
#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
int data;
struct Node *next;
} Node;
typedef struct Stack
{
Node *top;
} Stack;
Stack *create_stack()
{
Stack *s = malloc(sizeof(Stack));
s->top = NULL;
return s;
}
void push(Stack *s, int value)
{
Node *new_node = malloc(sizeof(Node));
new_node->data = value;
new_node->next = s->top;
s->top = new_node;
}
int pop(Stack *s)
{
if (s->top == NULL)
{
printf("Empty stack!\n");
return -1;
}
Node *temp = s->top;
int value = temp->data;
s->top = s->top->next;
free(temp);
return value;
}
int peek(Stack *s)
{
if (s->top == NULL)
{
printf("Empty Stack!\n");
return -1;
}
return s->top->data;
}
int is_empty(Stack *s)
{
return s->top == NULL;
}
void print_stack(Stack *s)
{
Node *curr = s->top;
printf("Stack (top -> bottom): ");
while (curr != NULL)
{
printf("%d ", curr->data);
curr = curr->next;
}
printf("\n");
}
void free_stack(Stack *s)
{
while (!is_empty(s))
{
pop(s);
}
free(s);
}
int main()
{
Stack *s = create_stack();
while (1)
{
int op;
printf("\n1) Push\n2) Pop\n3) Peek\n4) Print stack\n5) Exit\n> ");
scanf("%d", &op);
switch (op)
{
case 1:
{
int value;
printf("Enter a value: ");
scanf("%d", &value);
push(s, value);
break;
}
case 2:
printf("Pop: %d\n", pop(s));
break;
case 3:
printf("Top: %d\n", peek(s));
break;
case 4:
print_stack(s);
break;
default:
free_stack(s);
return 0;
}
}
}