1. 程式人生 > >資料結構——棧與佇列操作(用棧模擬佇列)

資料結構——棧與佇列操作(用棧模擬佇列)

【棧與佇列操作】
問題描述:假設有兩個長度相同的棧 S1,S2,已知以下入棧、出棧、判棧滿和判棧空操作:
void Push(S,x);
Elemtype Pop(S);
bool StackFull(S);
bool StackEmpty(S);
現用這兩個棧構成一個佇列,實現入佇列、出佇列操作的演算法:
bool EnQueue(x);
Elemtype DeQueue(S);

要求:
(1)設棧空間大小MaxSize=10,佇列的資料通過呼叫演算法initRandomize(int *arr, int n, int min, int max)隨機產生。
(2)測試環節要包含出佇列"空"和入佇列"滿"的情況出現。

知識點:
1.靜態棧的基本演算法(因為簡單,自定義函式短小,總覺得遺漏了些什麼)
2.用棧來模擬佇列(這裡就沒定義隊列了,棧S1就當作時隊列了,出佇列的時候借用棧S2來倒序輸出)
3.關於initRandomize(int *arr, int n, int min, int max)的使用
4.還有就是Sleep()、memset()的使用

自己基於【資料結構】【嚴蔚敏】版敲的
(網上應該會有許多更優的思路)
直接來完整程式碼:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h> #define OK 1 #define ERROR 0 #define OVERFLOW -1 #define TRUE 1 #define FALSE 0 #define MAXSIZE 10 //棧的大小和佇列的大小都是 10 typedef int Elemtype; typedef struct Stack { int data[MAXSIZE]; int top; // 棧頂指標 } SqStack; #include <time.h>
//time(0)需要的標頭檔案 (代表當前時間自標準時間戳(1970年1月1日0點0分0秒,GMT)經過了多少秒) void initRandomize(int *arr, int n, int min, int max) { int i = 0; srand(time(0)); /*設定種子,並生成偽隨機序列*/ for (i = 0; i < n; ++i) { arr[i] = rand()% (max - min + 1) + min; /*得到從[min, max]之間的隨機數*/ printf("%d ", arr[i]); } printf("\n"); } int InitStack(SqStack &S) //初始化靜態棧 { S.top=0; } int Push(SqStack &S,int e) { if(S.top>=MAXSIZE) return ERROR; S.data[S.top++]=e; return OK; } int Pop(SqStack &S,int &e) { if(S.top == 0) return ERROR; e=S.data[--S.top];//e=*(S.data+S.top-1) return OK; } int Empty(SqStack &S) { if(S.top == 0) return 1; else return 0; } int Full(SqStack S) { if(S.top == MAXSIZE) return 1; else return 0; } SqStack S1; SqStack S2; int EnQueue(int x)//進入佇列 { if(Full(S1)) { printf("佇列已滿\n"); } else Push(S1,x); } Elemtype DeQueue()//出佇列 { if(Empty(S1)) { printf("佇列為空\n"); } InitStack(S2); int e; while(!Empty(S1)) { Pop(S1,e); Push(S2,e); } while(!Empty(S2)) { Pop(S2,e); printf("%d ",e); } printf("\n\n\n"); } int EmptyStack(SqStack &S) //判斷棧是否為空 { if(Empty(S1)) return 1; else 0; } void test1() { int a[10],i; initRandomize(&a[0], 10, 1, 1002);//生成15個隨機數 InitStack(S1); for(i=0;i<10;i++) //溢位與不溢位關鍵看這裡讀入了幾個數,棧的大小等於佇列的大小 { EnQueue(a[i]); } printf("輸出佇列為:\n"); DeQueue(); //memset(a,0,sizeof(int)*10); } void test2() { int a[10]={1,2,3},i; initRandomize(&a[3], 10, 1, 1002); InitStack(S1); for(i=0;i<11;i++) //溢位與不溢位關鍵看這裡讀入了幾個數,棧的大小=佇列的大小=MAXSIZE=10 { EnQueue(a[i]); } if(i<=10) { printf("輸出佇列為:\n"); DeQueue(); } //memset(a,0,sizeof(int)*10); //printf("%d %d",a[0],*(a+3)); } void test3() { int a[10],i; initRandomize(&a[0], 10, 1, 1002); InitStack(S1); for(i=0;i<0;i++) //溢位與不溢位關鍵看這裡讀入了幾個數,棧的大小等於佇列的大小 { EnQueue(a[i]); } if(!Empty(S1)) { printf("輸出佇列為:\n"); DeQueue(); } else printf("佇列為空"); } int main() { test1(); //正常情況 Sleep(1000);//暫停1秒,變化種子點 test2(); // 溢位 test3(); // 為空 }