-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstacks-1.c
More file actions
54 lines (47 loc) · 950 Bytes
/
stacks-1.c
File metadata and controls
54 lines (47 loc) · 950 Bytes
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
#include<stdio.h>
#include<stdlib.h>
#include<limits.h>
struct Node {
int data;
struct Node* next;
};
struct Node* newNode(int data) {
struct Node* node = (struct Node*) malloc(sizeof(struct Node));
node->data = data;
node->next = NULL;
return node;
}
int isEmpty(struct Node* root) {
return !root;
}
void push(struct Node** root, int data) {
struct Node* node = newNode(data);
node->next = *root;
*root = node;
printf("%d pushed to stack\n", data);
}
int pop(struct Node** root) {
if(isEmpty(*root)) {
return INT_MIN;
}
struct Node* temp = *root;
*root = (*root)->next;
int popped = temp->data;
free(temp);
return popped;
}
int peek(struct Node** root) {
if(isEmpty(*root)) {
return INT_MIN;
}
return (*root)->data;
}
int main() {
struct Node* root = NULL;
push(&root, 10);
push(&root, 20);
push(&root, 30);
printf("%d popped from stack\n", pop(&root));
printf("Top element is %d\n", peek(&root));
return 0;
}