链表的方式实现栈

  • 栈的定义:只能在表的一端进行插入和删除元算的线性表,后进先出的规则,凡是在逻辑上需要“后进先出”的操作和过程都能用上栈。一些具体应用有:函数的求值,过程的调用与返回,递归过程的实现
  • 栈的基本运算:入栈(插入)、出栈(删除)、置栈空、判断是否为空、取栈顶元素
//stack chain storage structure
#include<iostream>
using namespace std;

class stack_chain;

class node{
public:
    friend class stack_chain;
private:
    char  _data;
    node* _next;
};

class stack_chain{
public:
    stack_chain(){_top=0;}
    ~stack_chain();     //release memory
    bool push(char& c); //push c into stack
    bool pop();  //remove an element from stack
    bool get_top(char& c); //get top element
    void clear();        //clear stack
    void display();
    
private:
    node* _top;
    int   _length;
};

stack_chain::~stack_chain(){
    clear();
}

bool stack_chain::push(char& c){
    node* tmp = new node;
    tmp->_data = c;
    tmp->_next=_top;
    _top= tmp;
    _length++;
    return true;
}

bool stack_chain::pop(){
    if(_top==0) return false;
    node* tmp=_top; 
    _top=tmp->_next;
    delete tmp;
    _length--;
    return true;
}

bool stack_chain::get_top(char& c){
    if(_top==0) return false;
    c=_top->_data;
    return true;
}

void stack_chain::clear(){
    node* tmp;
    while(_top!=0){
        tmp=_top;
        _top=_top->_next;;
        delete tmp;
    }
} 

void stack_chain::display(){
    node* tmp=_top->_next;
    while(tmp!=0){
        cout << tmp->_data;
        tmp= tmp->_next;
    }
    cout << endl;
}

int main(){
    char str[]="stack chain test...";
    stack_chain link;
    for(int i=0; str[i]!=0; i++) link.push(str[i]);
    link.display();
    link.pop();
    char t;
    link.get_top(t);
    cout << t << endl;
    link.clear();
    return 0;
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 1.栈 1.1.栈的定义 栈(stack)是限定仅在表尾(栈顶 top)进行插入和删除操作的后进先出的线性表。 p...
    JonyFang阅读 5,411评论 0 21
  • 栈是限定仅在表尾进行插入和删除操作的线性表。队列是只允许在一端进行插入操作,而在另一端进行删除操作的线性表。 栈的...
    Yix1a阅读 3,627评论 0 0
  • 好文笔不仅是读出来的,更是花时间记录、分析、比较、思考、创新出来的。如果仅仅是读,不走心,那么也是白读摆了! 《大...
    知瑜阅读 4,925评论 4 6
  • 昨夜喜降大雨, 今日清风送爽。 恰逢建军佳节, 军民欢聚一堂。 号角哒哒吹响, 国歌阵阵悠扬。 三军驰骋沙场, 飒...
    金赛月阅读 2,286评论 2 4
  • “人生如逆水行舟,不进则退。” 近来,一位朋友正为单位的变动焦虑。原本提供的免费宿舍,现在单位要整顿、收回,只租给...
    堂前花开阅读 3,142评论 0 4

友情链接更多精彩内容