-
Notifications
You must be signed in to change notification settings - Fork 0
/
schtack.c
63 lines (56 loc) · 1.44 KB
/
schtack.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
/* schtack.c */
# include <stdlib.h>
# include <stdio.h>
# include <string.h>
# include "schtack.h"
//////////////////////////////////////////
//new stack function
//returns a null valued pointer to a struct element i.e. the start of a stack
stack new () {
return NULL;
}
///////////////////////////////////////
//is_empty function
//checks if pointer is NULL and returns 0 if so
int isempty(stack s){
if(s) {
return 0;
} else {
return 1;
}
}
/////////////////////////////////////////
//push function
//creates a new struct element pointer, assigns memory space for its contents
//then sets the value of i to the int parameter, and the value of link to the
//stack pointer, then updates the stack pointer to point to the new element
//and returns it
stack push(stack s, int i){
struct element * e;
e = (struct element *) malloc(sizeof(struct element));
e->val = i;
e->link = s;
printf("Pushed %d to stack\n",i);
return e;
}
///////////////////////////////////////
//pop function
stack pop(stack s){
if (isempty(s)){
printf("Cannot pop. Stack is empty.\n");
return NULL;
}
printf("Popped top of stack\n");
free(s);
return s->link;
}
///////////////////////////////////////
//top function
int top(stack s){
if (isempty(s)){
printf("Cannot return value. Stack is empty.\n");
return 0;
}
printf("Top of stack is: %d\n",s->val);
return s->val;
}