C++:栈

栈是一种操作受限的线性表,栈的插入和删除都只允许在栈顶进行。

栈的基本元素有栈顶指针数据储存数组最大长度

栈的基本操作有init(构造)、flush(销毁)、push(数据压入栈顶)、pop(数据弹出栈顶)、empty(判空)、full(判满)、clear(清空数据)、size(当前长度)、top(获取栈顶元素)

根据储存方式的不同,可以分为顺序栈和链式栈

一、顺序栈

数据:栈顶指针、存储数组、最大容量

#include<bits/stdc++.h>
using namespace std;
 
template<class T>
class cStack
{
    int head;
    T * data;
    int maxSize;
public:
    cStack(int m)
    {
        head = -1;
        maxSize = m;
        data = new T[maxSize];
        count = 0;
    }
    ~cStack()
    {
        delete data;
    }
    bool empty()
    {
        return head == -1;
    }
    bool full()
    {
        return head == maxSize - 1;
    }
    void push(T x)
    {
        if (!full())
        {
            data[++head] = x;
        }
    }
    void pop()
    {
        if (!empty())
        {
            head--;
        }
    }
    T top()
    {
        return data[head];
    }
    void flush()
    {
        head = -1;
    }
    int size()
    {
        return head + 1;
    }
};

int main()
{
    cStack<int> s(1);
    cout << s.empty() << endl;
    s.push(6);
    cout << s.full() << endl;
    cout << s.top() << endl;
    s.pop();
    return 0;
}

二、链式栈

节点数据:存储数据、向下指针

栈数据:栈顶指针、节点数量

链式栈没有最大容量,因此没有full()判满函数

链式栈清空数据等同于释放节点

#include<bits/stdc++.h>
using namespace std;
 
template <class T>
class cNode  //单链表节点类.简单起见,成员均为public 
{
public:  
    T data;  //数据域  
    cNode<T> *next;  //指向下一个结点
 
    cNode(const T& item)
    {
        data = item;
        next = NULL;
    }
     ~cNode() { }
};
 

template<class T>
class cStack
{
    cNode<T> * head;
    int count;
public:
    cStack()
    {
        head = NULL;
        count = 0;
    }
    ~cStack()
    {
        flush();
    }
    T top()
    {
        return head->data;
    }
    void push(T x)
    {
        cNode<T> * p = new cNode<T>(x);
        p->next = head;
        head = p;
        count++;
    }
    void pop()
    {
        if (!empty())
        {
            return;
        }
        else
        {
            cNode<T> * p = head;
            head = head->next;
            delete p;
            count--;
        }
    }
    bool empty()
    {
        return !count;
    }
    int size()
    {
        return count;
    }
    void flush()
    {
        while(head)
        {
            cNode<T> *p = head;
            head = head->next;
            delete p;
        }
    }
};

int main()
{
    cStack<int> s;
    cout << s.empty() << endl;
    s.push(6);
    cout << s.top() << endl;
    s.pop();
    
    return 0;
}
 

三、C++自带的栈类

需要引入头文件

#include<stack>

定义栈对象,以int类型为例

stack<int> s;

该类的方法为,其中T为模板类型数据

bool empty(); // 如果栈为空返回1,否则返回0
// 没有判满函数full
void push(T x); // 栈顶压入元素x
void pop(); // 删除栈顶元素,无返回值
T top(); // 返回栈顶元素
int size(); // 返回当前栈的元素个数
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值