- 棧的定義:只能在表的一端進行插入和刪除元算的線性表,后進先出的規(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ā)布平臺,僅提供信息存儲服務。