C++实现Stack堆栈

//
// StackDemo Define the  entry point for the console application.
//
# include  < windows.h >
# include 
< stdio.h >

// 基本数据
struct   stUnit 
{
    
char  szName[ 64 ];
};
// 堆栈类
class  clStack
{
private :
    stUnit  
* mBuffer;
    unsigned  
int  mBufSize;
    unsigned 
int   mCount;
public :
    clStack(unsigned 
int  nBufSize):mBuffer(NULL),mBufSize( 0 ),mCount( 0 )
    {
        
if  (nBufSize < 10 )
        {
            nBufSize
= 10 ;
        }
        mBufSize
= nBufSize;
        mBuffer
= new  stUnit[mBufSize];
    }
    
~ clStack(){
        
if  (mBuffer != NULL){
         delete[] mBuffer;
         mBuffer
= NULL;
        }
        mCount
= 0 ;
        mBufSize
= 0 ;
    }
    
bool   Push(stUnit Unit){    // 将数据存入堆栈中
         if  (mCount >= mBufSize)    // 检查堆栈是否是满的
        {
            
return   false ;
        }
        mBuffer[mCount
++ ] = Unit;
        
return    true ;
    }
    
bool   Pop(stUnit &  Unit){

        
if  (mCount == 0 )   // 检查堆栈是否是空的
        {
            
return    false ;
        }
        
-- mCount;   
        Unit
= mBuffer[mCount];
        
return    true ;
    }
};
int  main( int  argc, char *  argv[])
{
    
int  loop;
    clStack  Stack(
10 );
    stUnit  People[
3 ];
    stUnit  Person;
    
// rson.szName="fdfdfdfd";
   
// trcpy(Person.szName,"fdfdfdfd");
    strcpy(People[ 0 ].szName, " Peter " );     // 建立三个人物的数据
    strcpy(People[ 1 ].szName, " Mary " );
    strcpy(People[
2 ].szName, " John " );


    
// push data into stack.
    printf( " push data into stack. " );
     
for  (loop = 0 ;loop < 3 ;loop ++ )
     {
         printf(
" %s " ,People[loop].szName);
         Stack.Push(People[loop]);
     }

     
// pop data from stack.
     printf( " Pop data from stack. " );
     
for  (loop = 0 ;loop < 3 ;loop ++ )
     {
        
if (Stack.Pop(Person))
        {
         printf(
" %s " ,Person.szName);
        }
     }
    
return   0 ;
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值