summaryrefslogtreecommitdiff
path: root/src/stack.c
blob: 2fe3488a6403f6a247a2a22513ea3fef4f34fa77 (plain)
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
#include "stack.h"
#include <stdio.h>

#define STACK_SIZE 100

struct stack_st {
    int len;
    int arr[STACK_SIZE];
};

struct stack_st stack = { .len = 0, .arr = {0}};

// Functions

void stackPush(int val){
  if (stack.len >= STACK_SIZE){
	printf("Stack overrflow\n");
	return;
  }
  stack.arr[stack.len] = val;
  stack.len++;
  return;
}


int stackPop(void){
  if (stackIsEmpty()){
	return 0;
  }
  int stackPopped = stack.arr[--stack.len];
  return stackPopped;
}


int stackIsEmpty(void) {
    return !(stack.len > 0);
}


int stackPeek(){
	// To avoid funking up the stack.len
	if (stackIsEmpty()) return 0;
	else if (stack.len == 1) return stack.arr[1];
	else{
		int x = stackPop();
		stackPush(x);
		return x;
	}
}


void stackPrint(){
	while(1){
		if(stackIsEmpty())
			break;

		int x = stackPop();
		printf("%d\n", x);
	}
	return;
}