/*
设计队列:
1、初始队列为空
2、入队允许队列增加
3、元素出队空间可以重复使用--整个队列的空间只增不减
题目源自王道数据结构,主要代码思路源自王道课本,部分添加
*/
#include <iostream>
#include <cstdlib>
using namespace std;
typedef char ElemType;
typedef struct LNode{
ElemType data;
struct LNode *next;
}*LinkList;
struct LinkQueue{
LinkList front, rear;
};
void InitList(LinkQueue &q){
q.rear = q.front = (LinkList)malloc(sizeof(LNode));
q.rear->next = q.front;
}
void EnQueue(LinkQueue &q, ElemType e){
if(q.rear->next==q.front){//队列满啦
LinkList s = (LinkList)malloc(sizeof(LNode));
s->next = q.rear->next;
q.rear->next = s;
q.rear->data = e;
}else{ //队不满
q.rear->data = e;
}
q.rear = q.rear->next;
}
void DeQueue(LinkQueue &q, ElemType &e){
if(q.front==q.rear){ //空队列情况
cout << "空队列" <<endl;
return;
}
e = q.front->data;
q.front = q.front->next;
}
void Print(LinkQueue q){
LinkList p = q.front;
while(p!=q.rear){
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
int main(){
LinkQueue q;
char c;
InitList(q);
while((c=getchar())!='\n'){
EnQueue(q, c);
}
cout << "队列初始元素:";
Print(q);
DeQueue(q, c);
cout << "出队元素:" ;
cout << c << endl;
cout << "出队元素:" ;
DeQueue(q, c);
cout << c << endl;
cout << "再次入队一个元素之后:" ;
EnQueue(q, 'c');
Print(q);
return 0;
}
循环单链表(空间只增不减)
最新推荐文章于 2023-02-24 21:10:35 发布