-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.c
101 lines (88 loc) · 1.8 KB
/
stack.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
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
/*
* stack.c
*
* Created on: 30 áéåì 2019
* Author: shake
*/
#include <stdlib.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include "Cell.h"
typedef struct {
int top;
int capacity;
Cell* array;
}Stack;
/*generate an empty stack*/
Stack* createStack(int capacity)
{
Stack* stack = (Stack*)malloc(sizeof(Stack));
if(stack == NULL)
{
printf("Error: malloc has failed.\n");
exit(0);
}
stack->capacity = capacity;
stack->top = -1;
stack->array = (Cell*)malloc(stack->capacity * sizeof(Cell));
if(stack->array == NULL)
{
printf("Error: malloc has failed.\n");
exit(0);
}
return stack;
}
/*check whether the stack is empty*/
int isEmpty(Stack* stack)
{
return stack->top == -1;
}
/*check whether the stack is full*/
int isFull(Stack* stack)
{
return stack->top == stack->capacity - 1;
}
/*add item to the top of the stack*/
void push(Stack* stack, Cell item)
{
if (isFull(stack))
return;
stack->top++;
stack->array[stack->top] = item;
}
/*remove item from the top of the stack*/
Cell* pop(Stack* stack)
{
if (isEmpty(stack))
return NULL;
return &(stack->array[stack->top--]);
}
/*return the item from the top of the stack*/
Cell* peek(Stack* stack)
{
if (isEmpty(stack))
return NULL;
return &(stack->array[stack->top]);
}
/*free all memories allocated to the stack*/
void freeStack(Stack* stack)
{
free(stack->array);
free(stack);
}
/*concatenate another stack to the top of the current stack*/
void concat(Stack* stack, Stack* another)
{
int num = another->top, i;
Stack* tempSt = createStack(stack->capacity);
for (i = 0; i <= num; i++)
{
push(tempSt, *pop(another));
}
for (i = 0; i <= num; i++)
{
push(stack, *pop(tempSt));
}
freeStack(tempSt);
}