00001
00002
00003 #include <cassert>
00004 #include <iostream>
00005 #include "Node.h"
00006
00007 using std::cout;
00008
00009
00010 Node::Node( int value )
00011 : pnext( NULL ), data( value )
00012 {
00013 }
00014
00015
00016 Node::Node( Node const& other )
00017 : pnext( NULL ), data( other.data )
00018 {
00019 }
00020
00021
00022 Node::~Node()
00023 {
00024 }
00025
00026
00027 void Node::insert( Node* newNode )
00028 {
00029 newNode->pnext = pnext;
00030 pnext = newNode;
00031 }
00032
00033
00034 void Node::remove_next()
00035 {
00036 if ( pnext == NULL ) return;
00037 Node* obsolete = pnext;
00038 this->pnext = obsolete->pnext;
00039
00040 obsolete->pnext = NULL;
00041 }
00042
00043
00044 bool Node::remove( Node* other )
00045 {
00046 Node* previous = this;
00047 Node* iter = pnext;
00048 while ( iter != other ) {
00049 if ( iter == NULL )
00050 return false;
00051 previous = iter;
00052 iter = iter->pnext;
00053 }
00054 previous->pnext = iter->pnext;
00055
00056 other->pnext = NULL;
00057 return true;
00058 }
00059
00060
00061 int Node::distance( Node const* other ) const
00062 {
00063 int hops = 1;
00064 Node const* iter = pnext;
00065 while ( iter != other ) {
00066 if ( iter == NULL ) {
00067
00068 return hops - 1;
00069 }
00070 iter = iter->pnext;
00071 ++hops;
00072 }
00073 return hops;
00074 }
00075
00076 size_t Node::size() const
00077 {
00078 return distance( NULL );
00079 }
00080
00081
00082 void print_list( Node const& head )
00083 {
00084 cout << '[' << head.size() << "] ";
00085 Node const* iter = &head;
00086 do {
00087 cout << iter->data << ' ';
00088 iter = iter->pnext;
00089
00090 } while ( iter != NULL );
00091 cout << '\n';
00092 }