#include<windows.h>
#include<iostream>
using namespace std ;
#define MaxSize 50
typedef char ElemType ;
typedef struct {
ElemType data [MaxSize] ;
int top ; //游标
} Stack ;
void InStack ( Stack *test ) {
// 初始化栈
test->top = -1 ;
}
bool IsEmpty (Stack *test) {
//判栈空
if(test->top == -1) {//说明栈的空的
return true ;
}
else return false ;
}
ElemType getTop (Stack *test) {
//返回栈顶的元素
if(!IsEmpty (test) ) {
return test->data[test->top] ;
}//弹出栈顶
}
void Pop (Stack *test) {
//弹出栈顶的元素
//if(!IsEmpty (test) ) {
cout << test->data [test->top] <<" " ;
test->top--;
//}
}
void Push (Stack *test , ElemType data ) {
//将元素data 放入栈
//需要判断会不会溢出
if( test->top > MaxSize -1) {
return ;
}
test->top++ ;
test->data [test->top ] = data ;
}
void Print (Stack *test) {
for(int i = 0;i <= test->top;i++)
cout <<test->data[i] << " " ;
}
int PrintLen (Stack *test) {
return test->top ;
}
void Delete (Stack *test) {
//清空
test->top = -1 ;
}
int main () {
Stack test;
cout <<"栈已经初始化。 "<<endl ;
InStack ( &test ) ;
if(!IsEmpty (&test)) cout <<"栈不为空 ! "<<endl;
else cout <<"栈为空 !"<<endl ;
cout <<"将元素 a b c d e 入栈"<<endl ;
Push (&test , 'a' ) ;Push (&test , 'b' ) ; Push (&test , 'c' ) ; Push (&test , 'd' ) ; Push (&test , 'e' ) ;
if(!IsEmpty (&test)) cout <<"栈不为空 ! "<<endl;
else cout <<"栈为空 !"<<endl ;
cout <<"此时栈的长度为 : ";
cout <<PrintLen (&test)+1<<endl;
Print (&test) ;
cout <<endl ;
if(!IsEmpty (&test)) cout <<"栈不为空 ! "<<endl;
else cout <<"栈为空 !"<<endl ;
cout <<"将元素出栈的顺序为 : " ;
for(int i =0;i<5; i++) {
Pop ( &test) ;
}
cout <<endl ;
if(!IsEmpty (&test)) cout <<"栈不为空 ! "<<endl;
else cout <<"栈为空 !"<<endl ;
Delete(&test) ;
cout <<"栈空间释放完毕."<<endl ;
system ("pause " ) ;
}
华南理工第三题 栈的各种操作
最新推荐文章于 2021-07-15 19:10:54 发布