#include using namespace std; class node { private: int payload; node *prev, *next; public: node(int i){ payload = i; prev = next = NULL; } node(int i, node *p, node *n){ payload = i; prev = p; next = n; } int get(){ return payload; } void print1(); void printprev(); void printnext(); void printall(); node *search(int); }; /* * search for, and insert if necessary, * a node containing data payload i. */ node * node::search(int i) { if (i == payload) /* found it here */ return this; else if (i < payload) { /* go left */ if (prev == NULL) { /* insert at beginning */ prev = new node(i, NULL, this); return prev; } else if (i > prev->get()) { /* insert */ node *mine = new node(i, prev, this); prev->next = mine; prev = mine; return mine; } else { /* search */ return prev->search(i); } } else if (i > payload) { if (next == NULL) { /* insert at end */ next = new node(i, this, NULL); return next; } if (i < next->get()) { /* insert */ node *mine = new node(i, this, next); next->prev = mine; next = mine; return mine; } else { /* search */ return next->search(i); } } } /* * Print one node's data payload. */ void node::print1() { cout << " " << payload << endl; } /* * Print all preceding nodes' payloads. */ void node::printprev() { if (prev) { prev->print1(); prev->printprev(); } } /* * Print all preceding nodes' payloads. */ void node::printprev_nonrecursive() { node *tmp = prev; while (tmp != NULL) { tmp->print1(); tmp = tmp->prev; } } /* * Print all preceding nodes' payloads. */ void node::kill_everything() { } /* * Print all succeeding nodes' payloads. */ void node::printnext() { if (next) { next->print1(); next->printnext(); } } /* * Print all nodes' payloads, starting from * wherever we are at. */ void node::printall() { cout << "The head is at " << payload << endl; cout << "Its fathers before it are:" << endl; printprev(); cout << "and its descendents are:" << endl; printnext(); } /* * demonstration data. */ int main() { node *mylist = new node(5); mylist = mylist->search(3); mylist = mylist->search(13); mylist = mylist->search(7); mylist = mylist->search(4); mylist = mylist->search(9); mylist = mylist->search(6); mylist->printall(); return 0; }