aboutsummaryrefslogtreecommitdiff
path: root/stack.c
blob: de5807c87dc4acea88a2314a07072df59f12ca88 (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
#include "stack.h"
#include <stdio.h>
#include <stdlib.h>

// Error handler for stack errors
void stack_error(int id)
{
	switch (id)
	{
	case 0:
		printf("Error: Stack overflow\nBe kind and report this problem.");
		break;
	case 1:
		printf("Error: Stack underflow\nBe kind and report this problem.");
		break;
	}
	exit(1);
}

// Creates a new stack
struct stack *create_stack(int capacity)
{
	struct stack *pt = (struct stack *)malloc(sizeof(struct stack));
	pt->max_size = capacity;
	pt->top = -1;
	pt->items = (int *)malloc(sizeof(int) * capacity);
	return pt;
}

// Adds a new item to a stack
void stack_push(struct stack *pt, int x)
{
	// Avoid a overflow by checking if the stack is full
	if (pt->top == pt->max_size - 1)
		stack_error(0);
	// Add an element and increase the top index
	pt->items[++pt->top] = x;
}

// Returns the topmost item of a stack
int stack_peek(struct stack *pt)
{
	// Check if the stack is empty
	if (pt->top == -1)
		stack_error(1);
	return pt->items[pt->top];
}

// Deletes the topmost item of a stack
int stack_pop(struct stack *pt)
{
	// Check for a stack underflow
	if (pt->top == -1)
		stack_error(0);
	// Decrease the stack size by 1 and (optionally) return the popped element
	return pt->items[pt->top--];
}