Escolar Documentos
Profissional Documentos
Cultura Documentos
//email: jiawei.gu777@gmail.com
/*problem:
Only given 2048 bytes, implement queue operation including create/destro
y/enqueue/dequeue.
There are various number of queues with various size.
*/
#include <iostream> //for on_out_of_memory() and on_illegal_operation() to print
stuff
namespace Sample
{
unsigned char data[2048] = { };
//VERY IMPORTANT!!
//Initialize() must be called to setup the data layout before doing anyt
hing to the data.
/*
data layout
Size
|Accumulated Memory
|Use
----------------------------|-------------------|-------------------8 bytes
|8 bytes
|Head
64 * 4 bytes = 256 bytes
e Header
223 * 8 bytes = 1784 bytes
a Blocks
*/
|264 bytes
|64 Queu
|2048 bytes
|223 Dat
struct Head
{
//total 8 bytes
unsigned char freeBlockHead;
ock
eue
unsigned char queueNum;
64
ated 223
unsigned char unusedByte[4];
};
struct Q
{
//total 32 bits = 4 bytes
unsigned char next : 8;
64 queues and NULL need 7 bits; 8 bits for wrapping
};
struct Block
{
//total 8 bytes
unsigned char next;
linked to this one
unsigned char data[7];
};
{
Head * head = GetHead();
head->freeBlockHead = 1;
head->freeQueueHead = 1;
head->queueNum = 64;
head->blockNum = 223;
}
}
// Pops the next byte off the FIFO queue
unsigned char dequeue_byte(Q * q)
{
//if head and tail are pointing the same position, it means the
queue is empty
if (q->headBlock == q->tailBlock && q->headOffset == q->tailOffs
et)
on_illegal_operation();
//Get the byte
unsigned char r = GetBlock(q->headBlock)->data[q->headOffset];
//Increase the head
++q->headOffset;
//Checking out of index
//data is using 0-6 for indexing; if it's 7, the head block shou
ld be freed
if (q->headOffset == 7)
{
Head * head = GetHead();
unsigned char freeBlock = q->headBlock;
//Goes to the next block
q->headBlock = GetBlock(q->headBlock)->next;
q->headOffset = 0;
//Free the block
FreeBlocks(freeBlock, freeBlock);
}
return r;
}
}
//A simple drive, uncomment if needed
//using namespace Sample;
//void main()
//{
//
Initialize();
//
//
Q * q0 = create_queue();
//
enqueue_byte(q0, 0);
//
enqueue_byte(q0, 1);
//
Q * q1 = create_queue();
//
enqueue_byte(q1, 3);
//
enqueue_byte(q0, 2);
//
enqueue_byte(q1, 4);
//
printf("%d", dequeue_byte(q0));
//
printf("%d\n", dequeue_byte(q0));
//
enqueue_byte(q0, 5);
//
enqueue_byte(q1, 6);
//
printf("%d", dequeue_byte(q0));
//
printf("%d\n", dequeue_byte(q0));
//
destroy_queue(q0);
//
printf("%d", dequeue_byte(q1));
//
printf("%d", dequeue_byte(q1));
//
printf("%d\n", dequeue_byte(q1));
//
destroy_queue(q1);
//
//
system("pause");
//}