View Single Post
Old 01-31-2005, 03:23 PM   #7 (permalink)
Valmont
[code][/code] enforcer
 
Valmont's Avatar
 
Join Date: Mar 2003
Location: Netherlands
Posts: 1,544
Valmont is on a distinguished road
Another (more professional) option is this:
Code:
#include <iostream>
#include <cstdlib>
#include <stdexcept>

using namespace std;

class Node
{
  public:
    Node() : next_(0)
    {}
    Node( int data, Node* nxt) : data_(data), next_(nxt)
    {}
    const int& get_data() const
    {
      return data_;
    }
    Node* next() const
    {
      return next_;
    }  
    private:
      friend class LinkedList;
      int data_;
      Node* next_;      
};

//--

class LinkedList
{
public:
  LinkedList();    
  ~LinkedList();
  void prepend(int const val);
  int const first() const;
  Node* get_head() const;
private:  
  Node* head_;
};

//-----------------------------------------

LinkedList::LinkedList() : head_(0)
{}

//------------------------------------------

LinkedList::~LinkedList()
{
  if(head_ != 0)
  {
    while(head_->next_ != 0)
    {
      Node* temp = head_;
      head_ = head_->next_;
      delete temp;
    }
    head_ = 0;
  }  
}

//------------------------------------------

void LinkedList::prepend(const int val)
{
  Node* const tmp = new Node(val, head_);
  head_ =  tmp;
}  

//------------------------------------------

const int LinkedList::first() const
{
  if(head_ == 0)
  {
    throw domain_error("ERROR: List is empty");
  }
  return head_->data_;    
}  

//------------------------------------------

Node* LinkedList::get_head() const
{
  return head_;
}  

//------------------------------------------

int main(int argc, char *argv[])
{
  LinkedList L;
  
  L.prepend(5);
  L.prepend(6);
  L.prepend(7);
  
  try
  {
    cout<<L.first()<<endl;
    for( Node* p = L.get_head(); p != 0; p=p->next() )
    {
      cout<<p->get_data()<<endl;
    }
  }
  catch(domain_error& dr)
  {
    cout<<dr.what()<<endl;
  }  

  return 0;
}
__________________

Last edited by Valmont; 01-31-2005 at 04:07 PM.
Valmont is offline   Reply With Quote