Deques
September 6, 2011
A normal linked list can be accessed only at its head. A double-ended queue, or deque (pronounced “deck”), can be accessed at either end. Like a normal list, a deque can be null. New elements can be added at either end, the element at either end of a non-null deque can be fetched, and the element at either end of a non-null deque can be deleted. Deques are a combination of stacks and queues.
Your task is to write a function library that implements deques; you should be sure that all operations are performed in constant time. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
In Racket:
Sometimes I wish I could delete my comments: my implementation doesn’t work at all (but soon I’ll be back :-) )
A ruby version …
It cheats a bit by using the ruby array and its assorted functions … but easy.
I’m practically just using normal haskell functions, wrapping them in a nice coat of Deque-ness! Kind of cheating, I know!
And of course I forgot the ‘add’ functions:
JavaScript & NodeJS:
An implementation in Racket using doubly linked lists.
With better amortisation: splitting a list in two when it is empty and accessed.
I put a purely functional version up on github the other day https://github.com/ijp/pfds/blob/master/deques.sls
Clojure: immutable, all operations in constant time thanks to clojure vector’s properties
A Python implementation. Keep in mind that I’m a new Python programmer, so this should not be considered an optimal implementation :)
class deque:
def __init__(self):
self._data = []
def add_front(self, i):
self._data.insert(0, i)
def add_back(self, i):
self._data.append(i)
def remove_front(self):
return self._data.pop(0)
def remove_back(self):
return self._data.pop()
def front(self):
return self._data[0]
def back(self):
return self._data[-1]
def is_empty(self):
return len(self._data) == 0
def __str__(self):
return self._data.__str__()
I can’t edit my post, so it would be nice if the previous post could be deleted. Here’s one that’s correctly formatted on pastbin.
source
C++ implementation