Академический Документы
Профессиональный Документы
Культура Документы
dnode
header
Doubly Linked List Implementation
template <typename T>
class dnode
{
public:
// the members of a dnode object are used for operations within a
// doubly linked list; access is simplified by making them public
// default constructor. creates object with value T(), the default value
// of type T. set the node pointers to point at the node itself
dnode();
}
Node Insertion
prevNode current node
prev next
newNode
dnode<T> *newNode, *prevNode;
// allocate a new node and assign prevNode to reference the predecessor of curr
newNode = new dnode<T>(item);
prevNode = curr->prev;
return newNode;
}
Node Deletion – Self Removal
curr
prevNode succNode
delete curr;
The erase() Function
template <typename T>
void erase(dnode<T> *curr)
{
// return if the list is empty
if (curr->next == curr)
return;
Simplify coding.
Avoid tests to determine if the list is empty.
Remove the additional code for updating the head pointer.
prev next
header An empty circular
linked list
while (p != header)
{
cout << p->nodeValue << separator;
p = p->next;
}
}
Application: The Josephus Problem
n customers to compete in a contest for a free world cruise.
3
9
The winner!
8 4
5
7
6
Solution to the Josephus Problem
void josephus(int n, int m)
{
// declare the circular doubly linked list dList and scan pointer
dnode<int> *dList = new dnode<int>, *curr;
int i, j;
Implementation of an iterator.
Private members:
dnode<T> *header;
int listSize;
dnode<T> *dinsert(dnode<T> *curr, const T& item); // insert before node curr and
// return address of the new node
void derase(dnode<T> *curr); // erase node curr from the linked list
A Constructor
// insert the values in the linked list obj.header at the back of the current list
while (curr != end)
{
dinsert(header, curr->nodeValue); // before the header, i.e., back of the list
curr = curr -> next;
}
}
Iterator Nested Class
class iterator
template <typename T> {
class miniList public:
{ friend class miniList<T>;
public:
// include the iterator // needed by the const_iterator constructor
// that converts a const iterator to a const_iterator
// nested classes friend class const_iterator;
#include “d_liter.h”
… // constructor
iterator() {}
private:
dnode<T> *header; bool operator==(const iterator& rhs) const;
int listSize; bool operator!= (const iterator& rhs) const;
T& operator* (); // pointer dereference operator
iterator& operator++ ();
dnode<T> *getDNode(
iterator operator++ (int) ; // postfix increment. move forward one no
const T& item); iterator& operator-- ();
dnode<T> *dinsert( iterator operator-- (int);
dnode<T> *curr, const T& item);
void derase(dnode<T> *curr); private:
}; dnode<T> *nodePtr; // pointer to the current list node
iterator& operator++ ()
{
nodePtr = nodePtr->next; // move to the successor of nodePtr
return *this; // return new iterator value
}