Thursday, 4 April 2013
DLL implemented
#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;
copy(D);
}
DLL& DLL::operator=(DLL& D){
while(del());
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;
if(_curr->_next){
_curr->_next->_prev = _curr->_prev;
}
else{
_tail = _tail->_prev;
}
if(_curr->_prev){
_curr->_prev->_next = _curr->_next;
}
else{
_head = _head->_next;
}
_curr = _curr->_next;
delete todel;
}
return ok;
}
void DLL::insert(int data){
if(_head == _curr){
_head = new Node(data, (Node*)0, _head);
_curr->_prev = _head;
}
else {
_curr->_prev = new Node(data, _curr->_prev, _curr);
_curr->_prev->_prev->_next = _curr->_prev;
}
}
int DLL::visit(){ // retruns data of current
return _curr->_data;
}
bool DLL::goHead(){
_curr = _head;
return (_curr != 0);
}
bool DLL::goTail(){
_curr = _tail;
return (_curr != 0);
}
bool DLL::goNext(){
bool rt = false;
if(_curr->_next){
rt = true;
_curr = _curr->_next;
}
return rt;
}
bool DLL::goPrev(){
bool rt = false;
if(_curr->_prev){
rt = true;
_curr = _curr->_prev;
}
return rt;
}
bool DLL::isEmpty(){
return !_head;
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment