notes72

notes72 - typedef EntryType int; class QueueArray : public...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
typedef EntryType int; class QueueArray : public Queue { int *array; // circular array int max; // max size int head; // points to front of queue int tail; // points to where new element is placed int n; // current elements in queue 0 max-1 a b c head ↑ tail ↑ public: QueueArray (int max) { _max = max; _head = 0; _tail = 0; _n = 0; _array = new int[max]; } void add (int element) { assert(_n < _max); _array[_tail] = element; _tail = (_tail + 1)%_max; // wrap if necessary _n++; } int remove() { assert(_n > 0); int tmp = _array[_head]; _head = (_head + 1) % max; _n--; return tmp; } } // QueueArray ( Circular Queue ) You can also implement a queue using a single-linked list. _head → P _tail → null You also need two pointers _head and _tail that point to beginning and end of the list. Initially _head → null _tail → null add(1) _head → 1 → null _tail add(3)
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
_head → 1 → 3 → null _tail remove() _head → 3 → null _tail return 1 Double Linked Lists - Removing an arbitary node from a single linked list takes time O(n) because we need to traverse the list to find previous node. Example: _head → q p _tail → null Remove node pointed by p. We need to find node previous to p (called q) and then make q → next = p → next
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 7

notes72 - typedef EntryType int; class QueueArray : public...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online