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

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

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

友情鏈接更多精彩內(nèi)容