//dataCell.h
class Data{
int data;
public:
Data(int d=0):data(d){}
int out()const{return data;}
};
//dllist.h
#include"node.h"
#include<iostream>
class DLList{
Node* front;
Node* back;
Node* current;
public:
DLList():front(NULL),back(NULL),current(NULL){}
virtual ~DLList(){
while(current=front){
front=front->next;
delete current;
}
}
void goBack(){current=back;}
void goFront(){current=front;}
void goNext(){
if(current)current=current->next;
}
void goPrev(){
if(current&¤t!=front)current=current->prev;
}
void remove(){
if(current){
Node* temp=current;
if(current==front)front=front->next;
else {
current->next->prev=current->prev;
current->prev->next=current->next;
current=current->next;
}
delete temp;
}
}
bool end(){
return !current;
}
Data get()const{
if(current){
//current->sayPos();
return current->data;
}
else return Data();
}
void insertBefore(const Data& a){
if(front){
if(current){
Node* p=new Node(a, current->next,current->prev);
if(p){
if(current->prev)current->prev->next=p;
else front=p;
current->prev=p;
}
}
else{
Node* p=new Node(a,current->next,current);
if(p)front=back=current=p;
}
}
}
void insertAfter(const Data& a){
if(current){
Node* p=new Node(a, current->next,current);
if(p){
if(current->next)current->next->prev=p;
else back=p;
current->next=p;
}
}
else{
Node* p=new Node(a,NULL,NULL);
if(p)front=back=current=p;
}
}
};
// node.h
#include"dataCell.h"
struct Node{
Data data;
Node* next;
Node* prev;
Node(const Data& d,Node* n,Node* p):data(d),next(n),prev(p){}
};
// doublelinks.cpp
#include"dllist.h"
using namespace std;
int menu(){
int x;
cout<<"Please make a selection"<<endl;
cout<<"1) Enter data before this position"<<endl<<"2) Enter data after this position"<<endl;
cout<<"3) Move ahead on list"<<endl<<"4) Move back on list"<<endl;
cout<<"5) Move to front of list"<<endl<<"6) Move to back of list"<<endl;
cout<<"7) Remove data at this position"<<endl<<"8) Print all data"<<endl;
cin >> x;
return x;
}
int main(){
//choice(DLList* r){
DLList r;
int x=0;
bool flip=false;
while(!flip){
switch(menu()){
case 1:
cout<<"Please input integer: ";
cin >> x;
r.insertBefore(x);
break;
case 2:
cout<<"Please input integer: ";
cin >> x;
r.insertAfter(x);
break;
case 3:
r.goNext();
cout<<"The data here is: "<<r.get().out();
break;
case 4:
r.goPrev();
cout<<"The data here is: "<<r.get().out();
break;
case 5:
r.goFront();
cout<<"The data here is: "<<r.get().out();
break;
case 6:
r.goBack();
cout<<"The data here is: "<<r.get().out();
break;
case 7:
r.remove();
cout<<"Data deleted";
break;
case 8:
while(!r.end()){
cout<<r.get().out()<<endl;
r.goNext();
}
r.goFront();
break;
default:
flip=true;
break;
};
cout<<endl;
}
return 0;
}
No comments:
Post a Comment