数据结构与算法分析100例之002(我自己敲的,我是菜鸟~!)

/*stack01.cpp********************************************************************************************|
|*the first example of  stacks**************************************************************************|
|*C++实现,Dev C++4.9.9.2编译通过(其实我用了C风格的C++,为了偷懒)**************|
|*欢迎提宝贵意见,本人是菜鸟! *******************************************************************|
|*数据结构与算法分析一百例之基本数据结构(编号002)***************************************/


//本程序包括栈的创建,销毁,判空,删除元素,插入元素%%%%%%%%%%%%%%%%%%%%%%%%%%%//
// 还包括栈的清空,求栈的长度,遍历(不过今天没写完)哈哈!%%%%%%%%%%%%%%%%%%%%%%%//
//参考书目:严蔚敏《数据结构(C语言版)》%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%//
//笑一笑!今天很好,明天会更好! %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%//

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <conio.h>

using namespace std;

#define STACK_INIT_SIZE 100 //存储空间初始分配量
#define  STACKINCREMENT 10  //存储空间分配增量
typedef int SElemType;
typedef struct {
        SElemType *base;
        SElemType *top;
        int stacksize;     //当前已分配存储空间,以元素为单位
}SqStack;

bool InitStack(SqStack &S){//构造一个空栈
    S.base= (SElemType *)malloc(STACK_INIT_SIZE*sizeof(SElemType));
    if(!S.base) 
        exit(1);          //存储分配失败
    S.top=S.base;
    S.stacksize=STACK_INIT_SIZE;
    return 1;
}

SElemType GetTop(SqStack S,SElemType &e){
          if(S.top==S.base)
            return 0;
            e=*(S.top-1);
            return e;
}

bool Push(SqStack &S,SElemType e){
          if(S.top-S.base>=S.stacksize){
             S.base= (SElemType *)realloc(S.base,(S.stacksize+STACKINCREMENT)
             *sizeof(SElemType));                          
          }
         if(!S.base) 
            exit(1);          //存储分配失败
            S.top=S.base+S.stacksize;
            S.stacksize+=STACKINCREMENT;
            *(S.top++)=e;
            cout<<"The input data is:"<<endl;
            cout<<e<<endl;
            return 1;
}
         
bool Pop(SqStack &S){
     SElemType e;
     if(S.top==S.base)
       return 0;
       e=*--S.top;
       cout<<"The output data is:"<<endl;
       cout<<e<<endl;
       return 1;     
}

int main(){
    char ch;                 //演示用,与栈无关
    SqStack  S;
    InitStack(S);  
    Push(S,5);
    Push(S,6);
    Push(S,5);
    Push(S,8);
    Pop(S);
    cin>>ch;                //演示用,与栈无关
    system("pause");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值