Wednesday, March 13, 2013

dll.cpp implement

#include "dll.h"
Node::Node(int data, Node* prev, Node* next){
  _data = data;
  _prev = prev;
  _next = next;
}

DLL::DLL(){
  _head = _tail = _curr = 0;
}

DLL::~DLL(){
  while(del());
}

void DLL::copy(DLL& D){
  int curpos;
  for(curpos=0;D.goPrev();curpos++); // findout where is current
  if(!D.isEmpty()){
    do{
      this->append(D.visit());
    }while(D.goNext());
  }
  for(D.goHead(), this->goHead();curpos;D.goNext(), this->goNext(),curpos--);
}

DLL::DLL(DLL& D){
  _head = _tail = _curr = 0;
  this->copy(D);
}

DLL& DLL::operator=(DLL& D){
  while(del());
  this->copy(D);
  return *this;
}

void DLL::append(int data){
  Node* newnode = new Node(data);
  if(_tail){  // ! empty
    _tail->_next = newnode;
    newnode->_prev = _tail;
    _tail = _curr = newnode;
  }
  else{
    _tail = _curr = _head = newnode;
  }
}

int DLL::remove(){
  int data = visit();
  del();
  return data;
}

bool DLL::del(){
  bool ok = false;
  if(_curr){
    ok = true;
    Node* todel = _curr;
    (_curr->_next) ? _curr->_next->_prev = _curr->_prev : _tail = _tail->_prev;
    (_curr->_prev) ? _curr->_prev->_next = _curr->_next : _head = _head->_next;
    (_curr->_next) ? _curr = _curr->_next : _curr = _curr->_prev;
    delete todel;
  }
  return ok;
}

void DLL::insert(int data){
    Node* toInsert = new Node(data);
    (_curr->_prev) ? (_curr->_prev->_next = toInsert) : (_head = toInsert);
    toInsert->_prev = _curr->_prev;
    toInsert->_next = _curr;
    _curr->_prev = toInsert;
    _curr = toInsert;    
}

int DLL::visit(){               // retruns data of current
    return _curr->_data;
}

bool DLL::goHead(){
    return ((_head) && (_curr = _head)) ? true : false;
}

bool DLL::goTail(){
    return ((_tail) && (_curr = _tail)) ? true : false;
}

bool DLL::goNext(){
    return ((_curr->_next) && (_curr = _curr->_next)) ? true : false;
}

bool DLL::goPrev(){
    return ((_curr->_prev) && (_curr = _curr->_prev)) ? true : false;
}

bool DLL::isEmpty(){
    return !_curr;
}

No comments:

Post a Comment