-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathStack.c
More file actions
76 lines (70 loc) · 1.64 KB
/
Stack.c
File metadata and controls
76 lines (70 loc) · 1.64 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
#include "Stack.h"
/**
* createStack - creates stack of given capacity
* @capacity: capacity of the stack
* Return: returns pointer to new stack otherwise NULL
*/
Stack *createStack(unsigned capacity)
{
Stack *stack = malloc(sizeof(Stack));
if (stack == NULL)
return NULL;
stack->capacity = capacity;
stack->top = -1;
stack->array = malloc(stack->capacity * sizeof(int));
return stack;
}
/**
* isFull - check if stack is full
* @stack: pointer to the stack to check
* Return: returns true if stack is full otherwise false
*/
int isFull(Stack *stack)
{
return stack->top == stack->capacity - 1;
}
/**
* isEmpty - check if stack is empty
* @stack: pointer to the stack to check
* Return: returns true if stack is empty otherwise false
*/
int isEmpty(Stack *stack)
{
return stack->top == -1;
}
/**
* push - add an item to the top of the stack
* @stack: pointer to the stack to check
* @item: item to add
*/
void push(Stack *stack, int item)
{
if (isFull(stack))
return;
stack->array[++stack->top] = item;
printf("%d pushed to stack\n", item);
}
/**
* pop - removes the top item
* @stack: pointer to the stack to check
* Return: returns the removed item or
* minimum int value if stack is empty
*/
int pop(Stack *stack)
{
if (isEmpty(stack))
return INT_MIN;
return stack->array[stack->top--];
}
/**
* peek - returns top item without removing it
* @stack: pointer to the stack to check
* Return: returns the top item or
* minimum int value if stack is empty
*/
int peek(Stack *stack)
{
if (isEmpty(stack))
return INT_MIN;
return stack->array[stack->top];
}