Queue = {}

function Queue:new()
	local o = {head = nil, tail = nil}

	setmetatable(o, self)
	self.__index = self
	return o
end

function Queue:enqueue(item)
	local elem = {item  = item}
	if self.head == nil then
		self.head = elem
		self.tail = elem
		return
	end

	elem.next = self.head
	elem.next.prev = elem
	self.head = elem
	return
end

function Queue:empty()
	return self.tail == nil
end

function Queue:dequeue()
	if self:empty() then
		return nil
	end

	local newtail = self.tail.prev
	local item = self.tail.item
	if newtail then
		newtail.next = nil
	end
	self.tail = newtail
	return item
end

local tq1 = Queue:new()
tq1:enqueue(5)
assert(tq1.head.item == 5)
assert(tq1:dequeue() == 5)

-- queue that keeps a rolling tally of its arguments
AvgQueue = {}

function AvgQueue:new(n, initial)
	local o = {}

	o.n = n
	o.queue = Queue:new()
	o.avg = initial


	local x = initial / n
	for _ = 1,n do
		o.queue:enqueue(x)
	end

	setmetatable(o, self)
	self.__index = self
	return o
end

function AvgQueue:push(item)
	local x = item/self.n
	self.avg = self.avg + x - self.queue:dequeue()
	self.queue:enqueue(x)
	return self.avg
end
