鏈表的方式實現(xiàn)棧

  • 棧的定義:只能在表的一端進行插入和刪除元算的線性表,后進先出的規(guī)則,凡是在邏輯上需要“后進先出”的操作和過程都能用上棧。一些具體應用有:函數(shù)的求值,過程的調用與返回,遞歸過程的實現(xiàn)
  • 棧的基本運算:入棧(插入)、出棧(刪除)、置棧空、判斷是否為空、取棧頂元素
//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;
}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 1.棧 1.1.棧的定義 棧(stack)是限定僅在表尾(棧頂 top)進行插入和刪除操作的后進先出的線性表。 p...
    JonyFang閱讀 1,385評論 0 21
  • 棧是限定僅在表尾進行插入和刪除操作的線性表。隊列是只允許在一端進行插入操作,而在另一端進行刪除操作的線性表。 棧的...
    Yix1a閱讀 537評論 0 0
  • 好文筆不僅是讀出來的,更是花時間記錄、分析、比較、思考、創(chuàng)新出來的。如果僅僅是讀,不走心,那么也是白讀擺了! 《大...
    知瑜閱讀 1,180評論 4 6
  • 昨夜喜降大雨, 今日清風送爽。 恰逢建軍佳節(jié), 軍民歡聚一堂。 號角噠噠吹響, 國歌陣陣悠揚。 三軍馳騁沙場, 颯...
    金賽月閱讀 288評論 2 4
  • “人生如逆水行舟,不進則退。” 近來,一位朋友正為單位的變動焦慮。原本提供的免費宿舍,現(xiàn)在單位要整頓、收回,只租給...
    堂前花開閱讀 407評論 0 4