注意:
(1 )如果我们需要通过函数修改顺序表内的信息,需要传递引用
(2 )如果我们只是读取顺序表内的内容,只需要传递指针
(3 )函数返回值使用bool 类型,用来返回状态,而其他的值可以使用引用的方式传进来;
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;
typedef int elmetype;
const int maxsize= 100 ;
typedef struct
{
elmetype date[ maxsize] ;
int top;
} Stack;
bool creat_stack ( Stack * & s)
{
s= ( Stack * ) malloc ( sizeof ( Stack) ) ;
if ( s== NULL ) return false ;
s- > top= - 1 ;
return true ;
}
void destroy_stack ( Stack * & s)
{
free ( s) ; return ;
}
bool judge_empty ( Stack * s)
{
return ( s- > top== - 1 ) ;
}
bool push_stack ( Stack * & s, elmetype x)
{
if ( s- > top== maxsize- 1 ) return false ;
s- > top++ ;
s- > date[ s- > top] = x;
return true ;
}
bool pop_stack ( Stack * & s)
{
if ( s- > top== - 1 ) return false ;
s- > top-- ;
return true ;
}
bool top_stack ( Stack * s, elmetype & x)
{
if ( s- > top== - 1 ) return false ;
x= s- > date[ s- > top] ;
return true ;
}
int main ( )
{
Stack * s;
bool f1= creat_stack ( s) ;
printf ( f1? "申请内存成功" : "申请内存失败" ) ;
destroy_stack ( s) ;
bool f2= judge_empty ( s) ;
printf ( f2? "栈为空" : "栈不空" ) ;
bool f3= push_stack ( s, 1 ) ;
printf ( f3? "栈满,插入失败" : "插入成功" ) ;
bool f4= pop_stack ( s) ;
printf ( f4? "成功弹出栈顶元素" : "栈为空,弹出失败" ) ;
elmetype x;
bool f5= top_stack ( s, x) ;
if ( f5) {
printf ( "栈顶元素为:%d" , x) ;
}
else {
printf ( "栈为空" ) ;
}
return 0 ;
}