数据结构之栈的操作实现

来源:互联网 发布:python生成100个随机数 编辑:程序博客网 时间:2024/05/29 08:57
#include <iostream>using namespace std;#define SIZEOFSTACK 8;//栈的定义typedef struct  {    int *top;    int *base;    int stacksize;}SqStack;//初始化一个栈int InitStack(SqStack &stack){    stack.base=new int;    if (!stack.base)    {        cout<<"存储初始化失败!"<<endl;        return 0;    }    stack.top=stack.base;  //空栈    stack.stacksize=SIZEOFSTACK;    return 0;}//插入元素bool Push(SqStack &stack,int value){    if (stack.top-stack.base>=stack.stacksize)    {        cout<<"栈满!无法插入元素!"<<endl;        return false;    }    *(stack.top)=value;      //栈的top指针指向栈顶的上一个元素    stack.top++;    return true;}//删除元素bool Pop(SqStack &stack,int &value)    //使用value保存删除的栈的元素的值{    if (stack.base==stack.top)    {        cout<<"栈为空,无法删除!"<<endl;        return false;    }    stack.top--;     value=*stack.top;//     value=*(--stack.top);    return true;}//获取栈的元素int GetStackvalue(SqStack &stack){    if (stack.top==stack.base)    {        cout<<"栈为空!"<<endl;        return -1;    }    int *p=stack.top-1;    while (p>=stack.base)    {        cout<<*(p)<<" ";        p--;    }    cout<<endl;    return 0;}void main(){    SqStack stack;    InitStack(stack);    int i=0;    while (i<10)    {        Push(stack,i*10);        i++;    }    GetStackvalue(stack);    int k;    Pop(stack,k);    Pop(stack,k);    GetStackvalue(stack);    cout<<"k="<<k<<endl;}

0 0
原创粉丝点击