-
Notifications
You must be signed in to change notification settings - Fork 1
/
myStack.c
85 lines (74 loc) · 1.56 KB
/
myStack.c
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
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "myStack.h"
const char* _MEM_ALLOC_ERROR_MSG = "Error in Heap Memory allocation.";
const char* _EMPTY_LIST_ERROR = "Stack is already empty. No more deletion possible.";
Stack* new_stack(){
Stack* temp = (Stack*) malloc(sizeof(Stack));
if(temp == NULL){
printf("%s :: Linked Stack\n", _MEM_ALLOC_ERROR_MSG);
return NULL;
}else{
temp -> head = NULL;
temp -> tail = NULL;
temp -> size = 0;
return temp;
}
}
Node* create_node(void* data){
Node* temp = (Node*) malloc(sizeof(Node));
if(temp == NULL){
printf("%s\n", _MEM_ALLOC_ERROR_MSG);
return NULL;
}else{
temp -> ele = data;
temp -> next = NULL;
return temp;
}
}
Stack* push(Stack* stack, void* data){
Node* new_node = create_node(data);
if(new_node == NULL){
return NULL;
}
if(stack -> size == 0){
stack -> head = new_node;
stack -> tail = new_node;
}else{
new_node -> next = stack -> head;
stack -> head = new_node;
}
stack -> size ++;
return stack;
}
Stack* pop(Stack* stack){
Node* del_node = stack -> head;
if(stack -> size == 0){
printf("%s\n", _EMPTY_LIST_ERROR);
return NULL;
}else if(stack -> size == 1){
stack -> head = NULL;
stack -> tail = NULL;
free(del_node);
}else{
stack -> head = stack -> head -> next;
free(del_node);
}
stack -> size --;
return stack;
}
void* top(Stack* stack){
if(stack -> head != NULL){
return stack -> head -> ele;
}else{
return NULL;
}
}
bool is_empty(Stack* stack){
if(stack -> size == 0){
return true;
}else{
return false;
}
}