Problem D: 栈的基本运算(栈和队列)
生活随笔
收集整理的這篇文章主要介紹了
Problem D: 栈的基本运算(栈和队列)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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
abcdeSample 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; }總結
以上是生活随笔為你收集整理的Problem D: 栈的基本运算(栈和队列)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【动态规划】0/1背包问题
- 下一篇: Frequent values【线段树】