[记录] 数据结构----栈的实现(顺序栈 链表栈)

/*
    栈顶指针就是链栈的头指针,指向一个空结点
*/
#include <iostream>
#include <cstdlib>
using namespace std;

typedef int ElementType;

class Node{
    friend class Stack;
private:
    ElementType data;
    Node* _next;
public:
    Node(ElementType data=1, Node* _next=NULL):data(data),_next(_next){}
    ~Node();
};

class Stack{
private:
    Node* head;//顺序栈基址
    int deepth;//栈尺寸
public:
    Stack();//初始化
    ~Stack();
    bool isEmpty();//判断栈空
    void makeEmpty();//使栈为空
    void push(ElementType e);//进栈
    ElementType pop();//出栈
    ElementType getTop();//返回栈顶元素
};
Stack::Stack(){
    head = new Node(0,NULL);
    deepth = 0;
}

bool Stack::isEmpty(){
    return deepth==0;//return head->_next==NULL
}
void Stack::makeEmpty(){
    while(!isEmpty()){
        pop();
    }
}
void Stack::push(ElementType e){
    Node* p = new Node(e, head->_next);
    if(!p)
        cout<<"Out of space";
    else{
        head->_next = p;
        deepth++;
    }
}

ElementType Stack::pop(){
    if(isEmpty()){
        cout<<"empty stack!";
        return 0;
    }
    else {
        Node *dele=head->_next;
        head->_next=dele->_next;
        ElementType e=dele->data;
        free(dele);
        deepth--;
        return e;
    }
}

ElementType Stack::getTop(){
    if(isEmpty()){
        cout<<"empty stack!";
        return 0;
    }
    else
        return head->_next->data;
}
int main(){}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值