单链表模拟循环队列

/*
带头结点的循环链表表示队列
只设一个指针指向队尾元素结点
编写相应的队列初始化、入队列和出队列的算法
*/
#include <iostream>
#include <cstdlib>
using namespace std;
const int flag = -1;
typedef struct Queue{
	int data;
	struct Queue *next;
}*LinkQueue;
LinkQueue initList(LinkQueue &Q){
	int x;
	Q = (LinkQueue)malloc(sizeof(Queue));
	LinkQueue r = Q;
	while(cin>>x && x!=flag){
		LinkQueue s = (LinkQueue)malloc(sizeof(Queue));
		s->data = x;
		r->next = s;
		r = s;
	}
	r->next = Q;
	return r;
}
void enQueue(LinkQueue &Q, int e){	//头进
	LinkQueue L = Q->next;	//循环链表的头结点
	LinkQueue s = (LinkQueue)malloc(sizeof(Queue));
	s->data = e;
	s->next = L->next;
	L->next = s;
}

void printQueue(LinkQueue Q){	//从头打印队列
	LinkQueue p = Q->next->next;
	cout << "当前队列元素:";
	while(p != Q->next){
		cout << p->data << " ";
		p = p->next;
	}
	cout << endl;
}

LinkQueue deQueue(LinkQueue &Q, int &e){	//尾出
	LinkQueue s, p;
	p = Q->next;	//找到头结点
	while(p->next != Q)	//找到尾结点的前一个结点
		p = p->next;
	s = p->next;	//要删除的结点
	e = s->data;
	p->next = s->next;
	free(s);
	return p; 
}

int main(){
	LinkQueue Q;
	int e;
	cout << "输入队列元素:";	//1 2 3 -1
	Q = initList(Q);
	printQueue(Q);
	
	//队列出队
//	Q = deQueue(Q, e);
//	printQueue(Q);
//	
//	Q = deQueue(Q, e);
//	printQueue(Q);
//
//	Q = deQueue(Q, e);
//	printQueue(Q);	
	
	//队列入队
	enQueue(Q, 10);
	printQueue(Q);
	
	enQueue(Q, 20);
	printQueue(Q);
	
	enQueue(Q, 20);
	printQueue(Q);
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值