// Oldham, Jeffrey D. // 2000Mar25 // CS1321 // Deque Implementation // This class implements a deque, a Double-Ended QUEue. ("Deque" is // pronounced "deck.") This data structure supports insertion and // deletion at both the front and the back in a constant amount of // time. In contrast, vectors support constant-time insertion and // deletion only at the back, i.e., right. // We implement a deque using a doubly-linked list. #include "dll.h" #include class deque { public: typedef dll::item_type item_type; // 0 typedef unsigned long size_type; // 4 // no need for a constructor // insertion routines void push_front(const item_type & i) {// 1 lst.insert(lst.begin(), i); return; } void push_back(const item_type & i) { // 1 lst.insert(lst.end(), i); return; } // checking for empty // 3 bool empty(void) const { return lst.begin() == lst.end(); } // removal routines void pop_front(void) { // 3 if (!empty()) lst.erase(lst.begin()); return; } void pop_back(void) { // 3 if (!empty()) lst.erase(lst.pred(lst.end())); return; } // access routines item_type& front(void) { // 4 if (!empty()) return lst.begin()->itm; else throw "deque: front() on empty deque"; } const item_type& front(void) const { // 4 if (!empty()) return lst.begin()->itm; else throw "deque: front() on empty deque"; } item_type& back(void) { // 4 if (!empty()) return lst.pred(lst.end())->itm; else throw "deque: back() on empty deque"; } const item_type& back(void) const { // 4 if (!empty()) return lst.pred(lst.end())->itm; else throw "deque: back() on empty deque"; } const item_type& operator[](size_type i) const { // 4 dll::link * l; for (l = lst.begin(); l != lst.end() && i > 0; l = lst.succ(l), i -= 1) ; if (i == 0 && l != lst.end()) return l->itm; else throw "deque: illegal element access"; } item_type& operator[](size_type i) { // 4 dll::link * l; for (l = lst.begin(); l != lst.end() && i > 0; l = lst.succ(l), i -= 1) ; if (i == 0 && l != lst.end()) return l->itm; else throw "deque: illegal element access"; } // output friend ostream& operator<<(ostream& out, const deque & dq) {// 2 for (dll::link * l = dq.lst.begin(); l != dq.lst.end(); l = dq.lst.succ(l)) out << l->itm; return out; } private: dll lst; // 0 };