//LinkQueue.h
#ifndef LinkQueue_H
#define LinkQueue_H
#define NULL 0
struct Node{
int data;
Node* next;
};
class LinkQueue{
public:
LinkQueue(); //构造
~LinkQueue(); //析构
void Enqueue(int x);// 插入
int DeQueue(); // 删除队首
int GetQueue(); //取队首元素
int Empty(); //判空操作
private:
Node* front; //队首指针
Node* rear; //队尾指针
};
#endif;
//LinkQueue.cpp
#include "LinkQueue.h"
LinkQueue::LinkQueue(){
Node* s = NULL;
s = new Node;
s->next = NULL;
front = rear = s;
}
LinkQueue::~LinkQueue(){
Node* p = NULL;
while(front!=NULL)
{
p = front->next;
delete front;
front = p;
}
}
void LinkQueue::Enqueue(int x){
Node* s = NULL;
s = new Node;
s->data = x;
s->next = NULL;
rear->next = s; rear = s;
}
int LinkQueue::DeQueue(){
Node* p = NULL;
int x;
if(rear == front) throw "下溢";
p = front->next;
x = p->data;
front->next = p->next;
if(p->next == NULL) rear = front;
delete p;
return x;
}
int LinkQueue::GetQueue(){
if(front!=rear) return front->next->data;
else return -(1<<30); //错误标记
}
int LinkQueue::Empty(){
if(front == rear) return 1;
return 0;
}
//LinkQueue_main.cpp
#include<iostream>
using namespace std;
#include "LinkQueue.h"
int main(){
LinkQueue Q;
if(Q.Empty()) cout << "队列为空" << endl;
else cout << "队列非空" << endl;
cout << "元素10和15执行入队操作:" << endl;
try{
Q.Enqueue(10);
Q.Enqueue(15);
}
catch(char* wrong){
cout << wrong << endl;
}
cout << "查看队首元素" << endl;
cout << Q.GetQueue() << endl;
cout << "执行出队操作" << endl;
try{
Q.DeQueue();
}
catch(char* wrong) {
cout << wrong << endl;
}
cout << "查看队首元素" << endl;
cout << Q.GetQueue() << endl;
return 0;
}