#include
#include
using namespace std;
//队列结点
struct queue_lnode {
int data;
queue_lnode* next;
};
//队列头指针和尾指针
struct queue_lr {
queue_lnode* rear;
queue_lnode* front;
};
//初始化一个队列
queue_lr* init_queue() {
queue_lr* p;
p = new queue_lr;
p->front = new queue_lnode;
p->rear = p->front;
(p->front)->data = 0;
return p;
}//入队
void push_queue(queue_lr* p, int data) {
queue_lnode* s = p->rear;
p->rear = new queue_lnode;
if ((p->rear) == nullptr) {
exit(-1);
}
p->rear->data = data;
(p->rear)->next = s->next;
s->next = p->rear;
cout << "成功进队一个元素" << endl;
return;
}
bool queue_is_empty(queue_lr* p) {
if (p->rear == p->front) {
return true;
}
return false;
}
//出队
int pop_queue(queue_lr* p) {
if (queue_is_empty(p)) {
cout << "queue is empty!" << endl;
exit(-1);
}
cout << "出队一个元素" << endl;
queue_lnode* rr = (p->front)->next;//定义一个指针指向队头
int data = rr->data;//将数据拷贝出来
(p->front)->next = rr->next;//将数据结点d出并删除
rr->next = nullptr;
delete rr;
return data;
}
int print_queue(queue_lr* p) {
queue_lnode* t = p->front->next;
int i = 0;
cout << "----打印队内元素---" << endl;
cout << "队头" << endl;
while (t != (p->rear)) {
cout << t->data << endl;
t = t->next;
i++;
}
cout << "队尾" << endl;
cout << "------------------" << endl;
return i;
}
int main() {
queue_lr* p = init_queue();
for (int i = 0; i < 5; i++) {
push_queue(p, i);
}
cout<<"当前队内元素个数:"<< print_queue(p) << endl;
for (int j = 0; j < 2; j++) {
cout << pop_queue(p) << endl;
}
cout << "当前队内元素个数:" << print_queue(p) << endl;
return 0;
}
以下为代码运行结果:
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)