using
System;
public
class
MainClass {
public
static
int
g = 0, k = 0;
public
class
Free {
public
int
tag;
public
int
size;
public
Free next;
}
public
static
Free free_head =
null
, prev_free =
null
;
public
class
Alloc {
public
int
block_id;
public
int
tag;
public
int
size;
public
Alloc next;
}
public
static
Alloc alloc_head =
null
, prev_alloc
=
null
;
public
static
void
CreateFree(
int
c)
{
Free p =
new
Free();
p.size = c;
p.tag = g;
p.next =
null
;
if
(free_head ==
null
)
free_head = p;
else
prev_free.next = p;
prev_free = p;
g++;
}
public
static
void
PrintFree()
{
Free p = free_head;
Console.WriteLine(
"Tag\tSize"
);
while
(p !=
null
) {
Console.WriteLine(p.tag +
"\t"
+ p.size);
p = p.next;
}
}
public
static
void
PrintAlloc()
{
Alloc p = alloc_head;
Console.WriteLine(
"Tag\tBlock ID\tSize"
);
while
(p !=
null
) {
Console.WriteLine(p.tag +
"\t "
+ p.block_id
+
"\t\t"
+ p.size);
p = p.next;
}
}
public
static
void
CreateAlloc(
int
c)
{
Alloc q =
new
Alloc();
q.size = c;
q.tag = k;
q.next =
null
;
Free p = free_head;
while
(p !=
null
) {
if
(q.size <= p.size)
break
;
p = p.next;
}
if
(p !=
null
) {
q.block_id = p.tag;
p.size -= q.size;
if
(alloc_head ==
null
)
alloc_head = q;
else
{
prev_alloc = alloc_head;
while
(prev_alloc.next !=
null
)
prev_alloc = prev_alloc.next;
prev_alloc.next = q;
}
k++;
}
else
Console.WriteLine(
"Block of size "
+ c
+
" can't be allocated"
);
}
public
static
void
DeleteAlloc(
int
t)
{
Alloc p = alloc_head, q =
null
;
while
(p !=
null
) {
if
(p.tag == t)
break
;
q = p;
p = p.next;
}
if
(p ==
null
)
Console.WriteLine(
"Tag ID doesn't exist"
);
else
if
(p == alloc_head)
alloc_head = alloc_head.next;
else
q.next = p.next;
Free temp = free_head;
while
(temp !=
null
) {
if
(temp.tag == p.block_id) {
temp.size += p.size;
break
;
}
temp = temp.next;
}
}
public
static
void
Main()
{
int
[] blockSize = { 100, 500, 200 };
int
[] processSize = { 417, 112, 426, 95 };
int
m = blockSize.Length;
int
n = processSize.Length;
for
(
int
i = 0; i < m; i++)
CreateFree(blockSize[i]);
for
(
int
i = 0; i < n; i++)
CreateAlloc(processSize[i]);
PrintAlloc();
DeleteAlloc(0);
CreateAlloc(426);
Console.WriteLine(
"After deleting block with tag id 0."
);
PrintAlloc();
}
}