Problem D: 棧的基本運算(棧和隊列)
Time Limit: 1 Sec??Memory Limit: 128 MBSubmit: 43??Solved: 15
[Submit][Status][Web Board]
Description
編寫一個程序,實現順序棧的各種基本運算,主函數已給出,請補充每一種方法。
?
1、初始化棧s;
2、判斷棧s是否非空;
3、進棧一個元素;
4、判讀棧s是否非空;
5、輸出棧長度;
6、輸出從棧頂到棧元素;
7、輸出出棧序列;
8、判斷棧s是否非空;
9、釋放棧;
?
數據元素類型定義為
typedef char ElemType;
?
順序棧的定義為
typedef struct
{
ElemType data[SizeMax];
int top;
}SqStack;
主函數:
int main()
{
SqStack *s;
InitStack(s); ? ? ? ? ? ? ? ? ? ? ? //初始化棧
if(StackEmpty(s))printf("空\n"); ? ?//判斷棧是否為空
else printf("非空\n");
ElemType a,b,c,d,e;
cin>>a>>b>>c>>d>>e;
Push(s,a); ? ? ? ? ? ? ? ? ? ? ? ? ?//入棧
Push(s,b);
Push(s,c);
Push(s,d);
Push(s,e);
if(StackEmpty(s))printf("空\n");
else printf("非空\n");
printf("棧的長度為%d\n",Length(s)); ?//輸出棧的長度
PrintStack(s); ? ? ? ? ? ? ? ? ? ? ? //輸出從棧頂到棧底的元素
Print(s); ? ? ? ? ? ? ? ? ? ? ? ? ? ?//輸出出棧序列
if(StackEmpty(s))printf("空\n");
else printf("非空\n");
DestroyStack(s); ? ? ? ? ? ? ? ? ? ? //釋放棧
return 0;
}
Input
輸入五個元素a,b,c,d,e;請根據題目編寫算法。
Output
Sample Input
abcde
Sample Output
空
非空
棧的長度為5
edcba
edcba
非空
HINT
請使用C++編譯并提交
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
using namespace std;
#define SizeMax 105
typedef char ElemType;
typedef struct
{ ElemType data[SizeMax]; int top;
}SqStack;void InitStack(SqStack *&s)
{ s= new SqStack; s->top=-1;
}
bool StackEmpty(SqStack *s)
{ return(s->top==-1);
}
bool Push(SqStack *&s,char e)
{ if(s->top==SizeMax-1)return false; s->top++; s->data[s->top]=e; return true;
}
int Length(SqStack*s)
{ return(s->top+1);
}
bool PrintStack(SqStack *s)
{ int i,e,a; a=s->top; if(s->top==-1)return false; for(i=-1;i<s->top;i++) { e=s->data[a]; a--; printf("%c",e); } printf("\n"); return true;
}
bool Print(SqStack *&s)
{ int i,e,a; a=s->top; if(s->top==-1)return false; for(i=-1;i<s->top;i++) { e=s->data[a]; a--; printf("%c",e); } printf("\n"); return true;
}
void DestroyStack(SqStack *&s)
{ delete(s);
}
int main()
{ SqStack *s; InitStack(s); //初始化棧 if(StackEmpty(s))printf("空\n"); //判斷棧是否為空 else printf("非空\n"); ElemType a,b,c,d,e; cin>>a>>b>>c>>d>>e; Push(s,a); //入棧 Push(s,b); Push(s,c); Push(s,d); Push(s,e); if(StackEmpty(s))printf("空\n"); else printf("非空\n"); printf("棧的長度為%d\n",Length(s)); //輸出棧的長度 PrintStack(s); //輸出從棧頂到棧底的元素 Print(s); //輸出出棧序列 if(StackEmpty(s))printf("空\n"); else printf("非空\n"); DestroyStack(s); //釋放棧 return 0;
}