Wednesday, 13 March 2013

DLL Program

Program of DLL
Function description:
1.DLL constructor
2.DLL destructor
3.DLL Copy constructor
4.DLL operator=()
5.DLL copy()
6.DLL append()
7.DLL insert()
8.DLL remove()
8.DLL del()
//dll.cpp
//HYQ
//Mar 14, 2013
//Release v0.3

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

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

DLL::DLL(DLL& D){//prevent copying
 _head = _tail = _curr = 0;
 copy(D);
} 

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

void DLL::copy(DLL& D){
  int currPos;
  for(currPos=0;D.goPrev();currPos++); // findout where is current
  if (!D.isEmpty()) {
    for(this->append(D.visit());D.goNext();this->append(D.visit()));
  }
  for(D.goHead(),this->goHead();currPos;D.goNext(),this->goNext(), currPos--); // set current to what it was before
}  


void DLL::append(int data){// add after tail
  Node* newNode = new Node(data, _tail);

  if (_tail!=0){
    _tail = _curr = _curr->_next = newNode;
  }
  else{
    _head = _tail = _curr = newNode;
  }
}

void DLL::insert(int data){// inserts data before current
  Node* newNode = new Node(data,_curr->_prev,_curr);
  
  if (!isEmpty()){
    if (_curr->_prev){
      _curr = _curr->_prev = _curr->_prev->_next = newNode;
    }
    else{
      _head = _curr = _curr->_prev = newNode;
    }
  }
  else{
    _head = _tail = _curr = newNode;
  }
}

int DLL::remove(){// remove the currect goes next if possible
 int data = visit();
 del();
 return data;
}


bool DLL::del(){
  bool ok;

  if (ok = !isEmpty()){
    Node* ToDel = _curr;
    
    if (_curr->_next){//NextNode exists, current node is not tail
      _curr->_next->_prev = _curr->_prev;
    }
    else{
      _tail = _tail->_prev;
    }

    if (_curr->_prev){//current node is not head
      _curr->_prev->_next = _curr->_next;
    }
    else{
       _head = _head->_next;
    }
    if(_curr->_next){
      _curr = _curr->_next;
    }
    else{
      _curr = _curr->_prev;
    }
    delete ToDel;
  }
  return ok;
}


No comments:

Post a Comment