栈和队列5--不带头指针的循环队列

#include<iostream>
#define MaxSize 200//循环队列最大长度
using namespace std;
typedef  int elem;//数据类型
typedef struct QNode {
	elem data;
	struct QNode *next;
}*QueuePtr;
typedef struct  {
	QueuePtr rear;//队尾
} LinkQueue;
bool init(LinkQueue &L) {
	L.rear->next= L.rear=new QNode;//头=尾
	return true;
}
//置空序列
bool initQueue(LinkQueue &l) {
	l.rear = l.rear->next;
	QueuePtr temp;
	while (l.rear != l.rear->next) {
		temp = l.rear->next;
		l.rear->next = temp->next;
		delete temp;
	}
	return true;
}
bool isEmpty(LinkQueue l) {
	return l.rear->next->next == l.rear->next;
	//判断头结点的后一个结点==头结点
}
bool push(LinkQueue &l, elem e) {
	QueuePtr temp=new QNode;
	temp->data = e;
	temp->next = l.rear->next;
	l.rear->next = temp;
	l.rear = temp;
	return true;
}
bool dequeue(LinkQueue &l,elem &e) {
	if (isEmpty(l)) return false;
	QueuePtr temp = l.rear->next->next;//头结点后的第一个元素结点"首元结点"
	e = temp->data;
	if (temp == l.rear) {		//队尾只剩下1个点
		l.rear = l.rear->next;	//尾指针指向头结点
		l.rear->next = temp->next;//头指向头
	}
	else
		l.rear->next->next = temp->next;
		//头的后一个指针指向原来的第二个结点的位置
		delete temp;
		return true;
}
bool show(LinkQueue l) {
	elem e;
	if (isEmpty(l)) return false;
	cout << "ShowTime" << endl;
	QueuePtr temp = l.rear->next->next; //头结点后的第一个元素结点"首元结点"
	while (temp!=l.rear->next) {
		e = temp->data;
		cout << e << " ";
		temp = temp->next;
	}
	return true;
}
int main() {
	LinkQueue S; elem e;
	if (init(S))	cout << "init Succeed" << endl;
	else cout << " init Failed" << endl;
	//入栈
	cout << "input e:\t";
	while (cin >> e) {//按"ctrl+z"结束输入
		push(S, e);
		cout << "input e:\t";
	}
	show(S);
	//出栈
	if (dequeue(S, e))
		cout << "移除的头元素是" << e << endl;
	else cout << "栈空" << endl;
	cout << "栈剩下所有元素为" << endl;
	show(S);
	initQueue(S);
	cout << "置空,栈剩下所有元素为" << endl;
	show(S);
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

广大菜鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值