Instructions
On your textbook page 92, Figure 3.10 shows code for a generic doubly linked list. However, our textbook does not show all the DoublyLinkedList member functions. So, we should define all the missing member functions. Textbook shows two member functions – addToDLLTail( ) and deleteFromDLLTail( ). The missing member functions are addToDLLHead( ), deleteFromDLLHead( ), and deleteDLLNode( ).
To complete this job, I will take deleteDLLNode( ), and you will complete addToDLLHead( ) and deleteFromDLLHead( ). To make your life a little easier, I add a HW6-template.CPP, which has all the code already written except ones for addToDLLHead and deleteFromDLLHead. Download this file and fill out the code for both member functions. This is a generic class, so study the existing code carefully how template <class T> is handled.
- Note that DLLNode now has two pointers - *next and *prev. So, when you write a code, you must consider values of both pointers.
and here is the program from the book.
Expand|Select|Wrap|Line Numbers
- #ifndef DOUBLY_LINKED_LIST
- #define DOUBLY_LINKED_LIST
- template<class T>
- class DLLNode {
- public:
- DLLNode() {
- next = prev = 0;
- }
- DLLNode(const T& el, DLLNode *n = 0, DLLNode *p = 0) {
- info = el; next = n; prev = p;
- }
- T info;
- DLLNode *next, *prev;
- };
- template<class T>
- class DoublyLinkedList {
- public:
- DoublyLinkedList() {
- head = tail = 0;
- }
- void addToDLLTail(const T&);
- T deleteFromDLLTail();
- . . . . . . . . . . . . .
- protected:
- DLLNode<T> *head, *tail;
- };
- template<class T>
- void DoublyLinkedList<T>::addToDLLTail(const T& el) {
- if (tail != 0) {
- tail = new DLLNode<T>(el,0,tail);
- tail->prev->next = tail;
- }
- else head = tail = new DLLNode<T>(el);
- }
- template<class T>
- T DoublyLinkedList<T>::deleteFromDLLTail() {
- T el = tail->info;
- if (head == tail) { // if only one node in the list;
- delete head;
- head = tail = 0;
- }
- else { // if more than one node in the list;
- tail = tail->prev;
- delete tail->next;
- tail->next = 0;
- }
- return el;
- }
- . . . . . . . . . . . . .
- #endif