8 线性表-循环队列-顺序存储

这几天犹豫了一下要不要上机实现数据结构的代码

一轮复习已经结束了

第二次看还是觉得光看书实在太无感了

于是决定来上机 顺便加深印象

即使考不上 记录一些基础的知识 以后找工作也有用……

好 就这样决定咧!不能偷懒!


1、循环队列:

实际上是把顺序队列臆造成一个环状的空间。

把存储队列元素的表从逻辑上看成一个环,称之为循环队列。

初始化时队首指针和队尾指针指向同一个存储空间,每次前进/后退一个位置都要进行(加减单位长度)%maxsize的处理

2、为了区分队空还是队满的情况有三种处理方式:

1)牺牲一个单元来区分队空或者队满的情况(下面算法就采用这个方式)

队满条件:(Q.rear+1)%maxsize==Q.fron

队空条件:Q.fron==Q.rear

队列中元素的个数:(Q.rear-Q.fron+maxsize)%maxsize

2)在类型中增设表示元素个数的数据成员。

队空的条件变为Q.size==0,队满的条件为Q.size==maxsize。

3)类型中增设tag数据成员,以区分队满还是队空。

tag=0:若是因为删除的情况导致Q.fron==Q.rear,队空

tag=1:若是因为增加的情况到时Q.fron==Q.rear,队满

3、注:出队要判空,入队要判满。一定要记住。

4、代码实现

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 #include<iostream>
 4 using namespace std;
 5 #define TRUE 1
 6 #define FALSE 0
 7 #define OK 1
 8 #define ERROR 0
 9 #define OVERFLOW -2
10 //#define STACK_INIT_SIZE 100//存储空间的初始分配量
11 //#define STACKINCREMENT 10//存储空间分配增量
12 #define maxsize 4
13 typedef struct
14 {
15     int data[maxsize];
16     int fron,rear;
17 } SqQueue;
18 
19 /*队列的初始化*/
20 /*注:出队前判队空,入队前判队满*/
21 void showmessage(int flag)
22 {
23     if(flag==1)
24     cout<<"the queue is already full, there is no place to put the data.";
25     else if(flag==2)
26     cout<<"there is no data in the queue.";
27     else cout<<"you were put the data successful!"<<endl;
28 }
29 void InitQueue(SqQueue *Q)
30 {
31     Q->rear=Q->fron=0;//初始化队首队尾指针
32 }
33 /*判断队是否为空*/
34 bool isEmpty(SqQueue *Q)
35 {
36     if(Q->rear==Q->fron)return TRUE;
37     else return FALSE;
38 }
39 bool EnQueue(SqQueue *Q,int x)
40 {
41     if((Q->rear+1)%maxsize==Q->fron) //如果此时已经到了队尾/采用(牺牲一个单元来区分队空或者队满的方法来区分队空或者队满的状态)
42     {
43         showmessage(1);
44         return 0;
45     }
46     else
47     {
48         Q->data[Q->rear]=x;
49         Q->rear=(Q->rear+1)%maxsize;
50         showmessage(3);
51     }
52     return OK;
53 }
54 
55 bool DeQueue(SqQueue *Q,int &ans)
56 {
57     if(isEmpty(Q))
58     {
59         showmessage(2);
60         return 0;
61     }
62     else
63     {
64         ans=Q->data[Q->fron];
65         Q->fron=(Q->fron+1)%maxsize;
66     }
67     return OK;
68 }
69 int main()
70 {
71     SqQueue *Q=(SqQueue *)malloc(sizeof(SqQueue));
72     InitQueue(Q);
73     int x;
74     for(int i=0;i<4;i++)
75     {
76         cin>>x;
77         EnQueue(Q,x);
78     }
79     cout<<endl;
80     cout<<"Now show you the data in the queue:";
81     while(!isEmpty(Q))
82     {
83         int ans;
84         DeQueue(Q,ans);
85         cout<<ans<<" ";
86     }
87     return 0;
88 }

5、代码实现截图

原文地址:https://www.cnblogs.com/AKsnoopy/p/7473711.html