学习数据结构基础,如有错误,请指正
/***
数据结构:队列的模拟,创建、销毁、进队列、出队列
打印输出字符,模拟先进现出特性
***/
#ifndef __LINKQUEUE_H__
#define __LINKQUEUE_H__
typedef char ElemType;
struct LinkNode{
ElemType data;
LinkNode *next;
};
class LinkQueue{
public:
LinkQueue();
~LinkQueue();
void enterQueue(ElemType e);
ElemType exitQueue();
void print();
private:
LinkNode *front;
LinkNode *rear;
void initLinkQueue();
void destroyLinkQueue();
};
#endif // __LINKQUEUE_H__
#include "LinkQueue.h"
#include <iostream>
using std::cout;
using std::endl;
LinkQueue::LinkQueue()
{
this->initLinkQueue();
}
LinkQueue::~LinkQueue()
{
this->destroyLinkQueue();
}
void LinkQueue::initLinkQueue()
{
this->front = new LinkNode();
if (!this->front)
{
exit(0);
}
this->rear = this->front;
this->front->next = NULL;
}
void LinkQueue::destroyLinkQueue()
{
#if 1
while (this->front != this->rear)
{
LinkNode *q = this->front->next;
this->front->next = q->next;
if (q == this->rear)
{
this->rear = this->front;
delete q;
}
}
#else
while(this->front){
this->rear = this->front->next;
delete this->front;
this->front= this->rear;
}
#endif
this->front = NULL;
this->rear = NULL;
}
void LinkQueue::enterQueue(ElemType e)
{
LinkNode *q = new LinkNode;
q->data =e;
q->next = NULL;
this->rear->next = q;
this->rear= q;
}
ElemType LinkQueue::exitQueue()
{
if (this->front == this->rear)
{
exit(0);
cout<<"queue is empty."<<endl;
}
LinkNode *q = this->front->next;
int e = q->data;
this->front->next = q->next;
if (q = this->rear)
{
this->front = this->rear;
}
return e;
}
void LinkQueue::print()
{
if (this->front == this->rear)
return;
LinkNode* q = this->front->next;
cout<<"print queue:"<<endl;
while(q){
cout<<q->data;
q = q->next;
}
}
int main()
{
LinkQueue *queue = new LinkQueue();
cout<<"enter queue:"<<endl;
for (int i=0;i <10;++i)
{
char aChar = rand()%20+40;
queue->enterQueue(aChar);
cout<<aChar;
}
cout<<endl;
queue->print();
getchar();
return 0;
}