-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.h
92 lines (70 loc) · 1.96 KB
/
stack.h
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
#pragma once
#include "headers.h"
struct stack{
int size; // actual used sized
int capacity; // maximum size available for usage
process **array;
} stack;
void stackInitialize(int inputSize) {
if(!inputSize || inputSize<1) inputSize = 200;
if(inputSize<200) inputSize = 200;
stack.array = malloc(inputSize*sizeof(process));
stack.size = 0;
stack.capacity = inputSize;
}
process* stackInsert(process* p) {
if(stack.size == stack.capacity) {
stack.capacity = stack.capacity * 2;
stack.array = realloc(stack.array,stack.capacity*sizeof(process));
}
process* to_insert = (process*) malloc(sizeof(process));
*to_insert = *p;
stack.array[stack.size++] = to_insert;
return to_insert;
}
bool stackRemove(process* p) {
int id = p->id;
process* remove = NULL;
for(int i=0;i<stack.size;i++) {
if(stack.array[i]->id == id) {
remove = stack.array[i];
stack.array[i] = stack.array[stack.size-1];
stack.size--;
break;
}
}
if(remove) {
free(remove);
return 1;
}
return 0;
}
void stackRefresh() {
for(int i=0;i<stack.size;i++) {
if(stack.array[i]->status == 1 || stack.array[i]->status==2) { //running process
stack.array[i]->remainingtime--;
}
else if(stack.array[i]->status == 3) { //waiting process
stack.array[i]->waitingtime++;
}
else if(stack.array[i]->status == 4) {
stackRemove(stack.array[i]);
}
}
}
process* stackGetProcess(int id) {
process *p = NULL;
for(int i=0;i<stack.size;i++) {
if(stack.array[i]->pid == id) {
p = stack.array[i];
break;
}
}
// if no process with such ID exists, NULL is returned (must check on NULL)
return p;
}
bool stackFree() {
for(int i=0;i<stack.size;i++) free(stack.array[i]);
free(stack.array);
return 1;
}