forked from gcsrilanka/Algorithm-Collection
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.c
More file actions
Latest commit
113 lines (81 loc) · 2.21 KB
/
Copy pathstack.c
File metadata and controls
113 lines (81 loc) · 2.21 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
#include<stdio.h>
#include<stdlib.h>
//self referencing structure with one data element
structNode {
intdata;
structNode*next;
};
// Aliasing for easier referencing
typedefstructNodeNode;
/*-------------------------------------- Stack Functions -------------------------------------- */
/** Ideally these should go in a seperate Header file (ie. stack.h) along with the self referencing structure
*
* Stack Functions
* Create Node : create_node
* Push : push (adds an item to the top of the stack)
* Pop : pop (removes the topmost item from the stack)
* Peek : peek (take a look at the topmost item without popping)
* Display Stack : print_stack
*
*/
Node*create_node(intdata) {
Node*new_node=malloc(1*sizeof(Node));
new_node->data=data;
new_node->next=NULL;
returnnew_node;
}
// adds a Node to the top of the stack
voidpush(Node**top, intdata) {
Node*new_node=create_node(data);
if(*top!=NULL) {
new_node->next=*top;
}
*top=new_node;
}
// Pops the Top Node from the Stack
intpop(Node**top) {
if(*top==NULL) {
printf("Popping Failed: Empty Stack !!\n");
return-1;
}
Node*popped=*top;
*top=popped->next;
intpopped_int=popped->data;
free(popped);
printf("Successfully Popped : %d\n", popped_int);
returnpopped_int;
}
// Prints all the elements in the Stack
voidprint_stack(Node*top) {
if(top==NULL) {
printf("Empty Stack!!\n");
return;
}
printf("[");
while(top!=NULL) {
printf(" %d", top->data);
if(top->next!=NULL) printf(",");
top=top->next;
}
printf(" ]\n");
}
//Prints the topmost item in the Stack
voidpeek(Node*top) {
if(top==NULL) {
printf("Empty Stack!!\n");
}else {
printf("First item of the Stack : %d\n", top->data);
}
}
/* --------------------------------- End of Stack Functions ----------------------------------- */
intmain() {
Node*stack=NULL;
push(&stack,10);
push(&stack,20);
push(&stack,50);
pop(&stack);
peek(stack);
push(&stack,40);
push(&stack,80);
print_stack(stack);
}