Wednesday, April 11, 2018

Implementation of a circular queue

public class CircularQueue {

private List<int> items;

private int head;

private int tail;

public CircularQueue(int capacity)

{

items = new List<int>(Enumerable.Repeat(capacity, 0));

head = 0;

tail = 0;

}

public void Enqueue(int val)

{

if (head == tail)

{

     // throw new UnsupportedException

     tail = (tail  + 1) % capacity;

}

items[head] = val;

head = (head + 1) % capacity;

}

public int Dequeue()

{

if (tail == head)

{

throw new UnsupportedException();

}

int val = items[tail];

tail = (tail + 1) % capacity;

return val;

}

}



head  tail

0       0



E

D

DE

DD

EE

ED

EDE

EED

DEE

EEE

DDD

DDE

#minesweeper

https://ideone.com/kPGtZ5

https://ideone.com/ACLtJs

No comments:

Post a Comment