- 棧的定義:只能在表的一端進(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ù)。