顺序栈

本文介绍了一个简单的顺序栈实现,包括基本操作如入栈、出栈、获取栈顶元素等,并提供了完整的C++代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

顺序栈

//
//  顺序栈
//
//  Created by chenshang on 14-2-6.
//  Copyright (c) 2014年 chenshang. All rights reserved.
//

#ifndef TestList_SeqStack_h
#define TestList_SeqStack_h

#include <iostream>
using namespace std;
typedef int T;
class SeqStack{
public:
    SeqStack(int sz):top(-1),MaxSize(sz)
    {
        arr = new T[sz];
        if (arr==NULL) {
            cout<<"application error"<<endl;
            exit(1);
        }
    }
    ~SeqStack(){
        delete[] arr;
    }
public:
    void push(T item);//入栈
    T pop();//出栈
    T getTop();//得到栈顶元素
    void print();//打印栈的元素
    //清空栈的数据
    void Empty(){
        top=-1;
    };
    bool isEmpty()const{
        return top==-1;
    }
    bool isFull()const{
        return top==MaxSize-1;
    }
private:
    int top;
    int *arr;
    int MaxSize;
};
void SeqStack::push(T item){
    if (isFull()) {
        cout<<"The stack is full"<<endl;
        return;
    }
    arr[++top]=item;
}
T SeqStack::pop(){
    if (isEmpty()) {
        cout<<"There is no element!"<<endl;
        exit(1);
    }
    //先返回top的值,然后再减一
    return arr[top--];
}
T SeqStack::getTop(){
    if (isEmpty()) {
        cout<<"There is no element!"<<endl;
        exit(1);
    }
    return arr[top];
}

void SeqStack::print(){
    cout<<"bottom";
    for (int i=0; i<=top; i++) {
        cout<<"-->"<<arr[i];
    }
    cout<<"-->top"<<endl<<endl<<endl;
}

#endif


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值