Код:
#include <assert.h>
#include <iostream>
using namespace std;
struct ListNode
{
char* data;
ListNode *nextPtr;
ListNode *prevPtr;
ListNode(char* value, ListNode *prev)
{
data=value;
nextPtr=NULL;
prevPtr=prev;
}
};
class queue
{
public:
queue();
~queue();
void InsertAtFront(char *);
void InsertAtBack(char *);
int RemoveFromFront(char *);
int RemoveFromBack(char *);
bool isEmpty()const;
void print()const;
int length();
friend ostream &operator<<(ostream &stream, queue *q);
friend istream &operator>>(istream &stream, queue *q);
ListNode *FirstPtr;
ListNode *LastPtr;
ListNode *GetNewNode(char *, ListNode *);
};
queue::queue()
{
FirstPtr=LastPtr=NULL;
}
queue::~queue()
{
if(!isEmpty())
{
cout<<"Удаление узлов..."<<endl;
ListNode*CurrentPtr=FirstPtr,*TempPtr;
while (CurrentPtr!=0)
{
TempPtr=CurrentPtr;
cout<<TempPtr->data<<endl;
CurrentPtr=CurrentPtr->nextPtr;
delete TempPtr;
}
}
cout<<"Все узлы удалены!"<<endl;
}
void queue::InsertAtFront(char *value)
{
ListNode *ptr=GetNewNode(value, NULL);
if(isEmpty()) FirstPtr=LastPtr=ptr;
else
{
ptr->nextPtr=FirstPtr;
FirstPtr=ptr;
}
cout << "Узел добавлен в начало!" << endl;
}
void queue::InsertAtBack(char *value)
{
ListNode *ptr=GetNewNode(value, LastPtr);
if(isEmpty()) FirstPtr=LastPtr=ptr;
else
{
LastPtr->nextPtr=ptr;
LastPtr=LastPtr->nextPtr;
}
cout << "Узел добавлен в конец!" << endl;
}
int queue::RemoveFromFront(char *value)
{
if(isEmpty())
{
cout << "Очередь пуста!" << endl;
return 0;
}
ListNode *ptr=FirstPtr;
strcpy(value,ptr->data);
if(FirstPtr==LastPtr) FirstPtr=LastPtr=NULL;
else
{
FirstPtr=FirstPtr->nextPtr;
FirstPtr->prevPtr=NULL;
}
delete ptr;
cout << "Узел удалён из начала очереди!" << endl;
return 1;
}
int queue::RemoveFromBack(char *value)
{
if(isEmpty())
{
cout << "Очередь пуста!" << endl;
return 0;
}
ListNode *ptr=LastPtr;
strcpy(value,ptr->data);
if(FirstPtr==LastPtr) FirstPtr=LastPtr=NULL;
else
{
LastPtr=LastPtr->prevPtr;
LastPtr->nextPtr=NULL;
}
delete ptr;
cout << "Узел удалён из конца очереди!" << endl;
return 1;
}
bool queue::isEmpty()const
{
return FirstPtr==NULL;
}
ListNode* queue::GetNewNode(char *value, ListNode *prev)
{
ListNode *ptr = new ListNode(value,prev);
assert(ptr!=0);
return ptr;
}
void queue::print()const
{
if(isEmpty())
{
cout<<"Очередь пуста!"<<endl;
return;
}
ListNode *CurrentPtr=FirstPtr;
cout<<"Очередь состоит из:"<<endl;
while(CurrentPtr!=0)
{
cout<<CurrentPtr->data<<endl;
CurrentPtr=CurrentPtr->nextPtr;
}
cout<<endl<<endl;
}
int queue::length()
{
int k=0;
ListNode *tmp=FirstPtr;
while(tmp)
{
tmp=tmp->nextPtr;
k++;
}
return k;
}
ostream &operator<<(ostream &stream, queue *q)
{
ListNode *tmp=q->FirstPtr;
while(tmp)
{
stream << tmp->data << " ";
tmp=tmp->nextPtr;
}
stream << endl;
return stream;
}
istream &operator>>(istream &stream, queue *q)
{
char *data=new char;
fflush(stdin);
stream.getline(data,256);
q->InsertAtBack(data);
return stream;
}