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
總結
以上是生活随笔為你收集整理的8 线性表-循环队列-顺序存储的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 03-Flutter移动电商实战-底部导
- 下一篇: 关于高等数学、线性代数、数理统计和概率论