生活随笔
收集整理的這篇文章主要介紹了
数据结构——栈与队列操作(用栈模拟队列)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
【棧與隊列操作】 問題描述:假設有兩個長度相同的棧 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 typedef int Elemtype
;
typedef struct Stack
{ int data
[ MAXSIZE
] ; int top
;
} SqStack
; #include <time.h>
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
; 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
] ; 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 ) ; InitStack ( S1
) ; for ( i
= 0 ; i
< 10 ; i
++ ) { EnQueue ( a
[ i
] ) ; } printf ( "輸出隊列為:\n" ) ; DeQueue ( ) ;
} void test2 ( )
{ int a
[ 10 ] = { 1 , 2 , 3 } , i
; initRandomize ( & a
[ 3 ] , 10 , 1 , 1002 ) ; InitStack ( S1
) ; for ( i
= 0 ; i
< 11 ; i
++ ) { EnQueue ( a
[ i
] ) ; } if ( i
<= 10 ) { printf ( "輸出隊列為:\n" ) ; DeQueue ( ) ; }
} 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 ) ; test2 ( ) ; test3 ( ) ;
}
轉載于:https://www.cnblogs.com/vivid-victory/p/10090473.html
總結
以上是生活随笔 為你收集整理的数据结构——栈与队列操作(用栈模拟队列) 的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔 網站內容還不錯,歡迎將生活随笔 推薦給好友。