栈的实现和基本操作

来源:互联网 发布:什么时候开放网络购彩 编辑:程序博客网 时间:2024/06/05 09:39

栈是一种常用的数据结构,可以帮助我们有效地保存临时数据.它遵循LIFO(Last In First Out)的原则.
它有push(),pop(),isEmpty(),isFull()几个常用操作.今天我们就试着用C++来创建一个栈,并用函数表达出这些功能.

#include<iostream>#include<cstdio>using namespace std;int Stack[1000],top=-1;bool isFull(){    if(top==999)    {        return true;    }    else    {        return false;    }}bool isEmpty(){    if(top==-1)    {        return true;    }    else    {        return false;    }}void push(int num){    if(!isFull())    {    Stack[top+1]=num;    top++;    }    else    {        printf("The stack is full.")    }}int pop(){    if(!isEmpty)    {        int num=Stack[top];        top--;        return num;    }    else    {        printf("The stack is empty.")    }}int main(){    return 0;}

像这样我们就可以构建出一个以Stack[0]为底的栈,并且实现这四个基本操作.

原创粉丝点击