双栈模拟队列
基本思路:队列是先进先出,栈是先进后出。用一个输入栈存进队元素,用一个输出栈将输出栈中的元素倒置,再出栈。这就实现了队列的先进先出。
注意:队满的条件为输入栈S1满且输出栈S2非空。并非输入栈满就代表队列满,因为如果输入栈满但输出栈空,可以将输出栈中的元素全部压入输出栈中,这就相当于队列没满,同时如果输出栈中有元素,则输入栈中的元素不能压入输出栈,如果压入就会打乱原有的序列。
#include<stdio.h>
#include<stdlib.h>
#define maxsize 30
typedef int datatype;
typedef struct{
datatype data[maxsize];
int top;
}SeqStack;
void Initial(SeqStack *S){
S->top = -1;
}
int StackIsFull(SeqStack *S){
return S->top == maxsize-1;
}
int StackIsEmpty(SeqStack *S){
return S->top == -1;
}
int StackPop(SeqStack *S){
int k;
if(StackIsEmpty(S))
return 0;
k = S->data[S->top--];
return k;
}
int StackPush(SeqStack *S,datatype x){
if(StackIsFull(S))
return 0;
S->data[++S->top]=x;
return 1;
}
//判断队空
int QueueIsEmpty(SeqStack *S1,SeqStack *S2){
return StackIsEmpty(S1)&&StackIsEmpty(S2);
}
//进队列
int EnQueue(SeqStack *S1,SeqStack *S2,datatype x){
if(StackIsFull(S1)){
if(!StackIsEmpty(S2)){
printf("用栈模拟的队列已满");
return 0;
}
else{
int k;
while(!StackIsEmpty(S1)){
k = StackPop(S1);
StackPush(S2,k);
}
}
}
StackPush(S1,x);
return 1;
}
// 出队列
int DeQueue(SeqStack *S1,SeqStack *S2){
int k;
if(QueueIsEmpty(S1,S2)){
printf("用栈模拟的队列已空");
return 0;
}
else{
if(StackIsEmpty(S2)){
while(!StackIsEmpty(S1)){
k = StackPop(S1);
StackPush(S2,k);
}
}
}
return StackPop(S2);
}
void ImitateQueue(SeqStack *S1,SeqStack *S2){
Initial(S1);
Initial(S2);
int x;
printf("请输入进队元素:");
scanf("%d",&x);
while(x!=0){
EnQueue(S1,S2,x);
scanf("%d",&x);
}
printf("出队元素为:");
while(!QueueIsEmpty(S1,S2)){
int k;
k = DeQueue(S1,S2);
printf("%d",k);
}
}
main(){
SeqStack *S1 = (SeqStack*)malloc(sizeof(SeqStack));
SeqStack *S2 = (SeqStack*)malloc(sizeof(SeqStack));
ImitateQueue(S1,S2);
}
铁道车厢调度问题
基本思路:用一个栈
#include<stdio.h>
#include<stdlib.h>
#define maxsize 30
typedef struct {
char data[maxsize];
int top;
}SeqStack;
void Initial(SeqStack *S){
S->top = -1;
}
int IsFull(SeqStack *S){
return S->top==maxsize-1;
}
int IsEmpty(SeqStack *S){
return S->top==-1;
}
int Push(SeqStack *S,char x){
if(IsFull(S))
return 0;
S->data[++S->top]=x;
return 1;
}
char Pop(SeqStack *S){
char c;
if(IsEmpty (S))
return 0;
c = S->data[S->top];
S->top--;
return c;
}
void Railway(SeqStack *S){
int i,j=0,n=9;
char train[n] = {'H','S','H','H','S','H','S','S','H'},result[n];
for(i=0;i<n;i++){
if(train[i]=='S')
result[j++]=train[i];
else{
Push(S,train[i]);
}
}
while(!IsEmpty(S)){
for(;j<n;j++){
result[j]=Pop(S);
}
}
for(j=0;j<n;j++){
printf("%c",result[j]);
}
}
main(){
SeqStack *S = (SeqStack*)malloc(sizeof(SeqStack));
Initial(S);
printf("jjjj");
Railway(S);
}
原文地址:https://www.cnblogs.com/susususu/p/10854009.html
时间: 2024-10-12 01:48:39