-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack_linkedlist.c
More file actions
executable file
·139 lines (122 loc) · 2.13 KB
/
stack_linkedlist.c
File metadata and controls
executable file
·139 lines (122 loc) · 2.13 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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
/**
* Last In First Out (LIFO)
*/
#include <stdio.h>
#include <stdlib.h>
#include "stack.h"
/**
* struct node - A node for the stack.
*
* @value: The value stored in the node.
* @next: A pointer to the next node in the stack.
*/
struct node
{
int value;
struct node *next;
} *top = NULL;
int main(void)
{
printf("Before push()\n");
push(10);
push(20);
push(30);
print_stack();
pop();
print_stack();
printf("Peek = %d\n", peek());
free_stack();
top = NULL; // Reset the top pointer after freeing
return 0;
}
/**
* is_empty - Checks if the stack is empty.
*
* Returns: 1 if the stack is empty, 0 otherwise.
*/
int is_empty()
{
if (top == NULL)
return 1;
else
return 0;
}
/**
* push - Pushes an element onto the stack.
* @value: The value to be pushed onto the stack.
*/
void push(int value)
{
struct node *new = malloc(sizeof(struct node));
if (!new)
{
printf("Stack overflow\n");
exit(1);
}
new->value = value;
new->next = top;
top = new;
}
/**
* pop - Pops an element from the stack.
*
* Returns: The value of the popped element.
*/
int pop()
{
struct node *temp = top;
if (is_empty())
{
printf("Stack overflow\n");
exit(1);
}
int value = temp->value;
top = top->next;
free(temp);
temp = NULL;
return value;
}
/**
* peek - Returns the value of the top element without removing it.
*
* Returns: The value of the top element.
*/
int peek()
{
if (is_empty())
{
printf("Stack overflow\n");
exit(1);
}
return top->value;
}
/**
* print_stack - Prints the elements in the stack.
*/
void print_stack()
{
struct node *ptr = top;
if (is_empty())
{
printf("Stack overflow\n");
exit(1);
}
printf("Stack elements are:\n");
while (ptr)
{
printf("%d\n", ptr->value);
ptr = ptr->next;
}
}
/**
* free_stack - Frees all the memory occupied by the stack nodes.
*/
void free_stack()
{
while (top)
{
struct node *temp = top;
top = top->next;
free(temp);
}
}