-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack.h
101 lines (87 loc) · 2.41 KB
/
stack.h
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
#ifndef _STACK_H_
#define _STACK_H_
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
struct StackNode {
int data;
struct StackNode* next;
};
struct StackNode* newNode(int data)
{
struct StackNode* stackNode = (struct StackNode*)malloc(sizeof(struct StackNode));
stackNode->data = data;
stackNode->next = NULL;
return stackNode;
}
int isEmpty(struct StackNode* root)
{
return !root;
}
void push(struct StackNode** root, int data)
{
struct StackNode* stackNode = newNode(data);
stackNode->next = *root;
*root = stackNode;
}
int pop(struct StackNode** root)
{
if (isEmpty(*root))
return INT_MIN;
struct StackNode* temp = *root;
*root = (*root)->next;
int popped = temp->data;
free(temp);
return popped;
}
int peek(struct StackNode* root)
{
if (isEmpty(root))
return INT_MIN;
return root->data;
}
int size(struct StackNode** root){
if (isEmpty(*root))
return 0;
int size = 0;
struct StackNode* current = *root;
while (current != NULL){
++size;
current = current->next;
}
return size;
}
void clear(struct StackNode** root){
if (!isEmpty(*root)){
int tempSize = size(root);
for (int i = 0; i < tempSize; i ++){
*root = (*root)->next;
}
} else {
printf("stack is empty\n");
}
}
void reverse(struct StackNode** root){
if (!isEmpty(*root)){
struct StackNode* temp;
while (!isEmpty(*root))
{
push(&temp, pop(root));
}
*root = temp;
}
}
void fullPrint(struct StackNode** root){
if (!isEmpty(*root)){
struct StackNode* temp = *root;
reverse(&temp);
int tempSize = size(&temp);
for (int i = 0; i < tempSize; i ++){
printf("%d ", pop(&temp));
}
printf("\n");
} else {
printf("stack is empty\n");
}
}
#endif