c++ 鏈式棧
阿新 • • 發佈:2019-01-03
鏈式棧:
檔名:LinkedStack.h
#include
#include
using namespace std;
#include "static.h"
template
struct LinkNode{
T data;
LinkNode* link;
LinkNode(LinkNode* ptr = NULL){
link = ptr;
}
LinkNode(const T& item, LinkNode* ptr =
NULL){
data = item;
link = ptr;
}
};
template
class LinkedStack;
template
std::ostream&
operator<<(std::ostream& os, LinkedStack&
s);
template
class LinkedStack:public Stack{
public:
LinkedStack():top(NULL){};
~LinkedStack(){makeEmpty();};
void Push(const T& x);
bool Pop(T& x);
bool getTop(T& x) const;
bool IsFull(){};
bool IsEmpty() const{
return (top == NULL) ? true :
false;
}
int getSize() const;
void makeEmpty();
friend std::ostream&
operator<< (std::ostream& os, LinkedStack&
s);
private:
LinkNode* top;
};
template
void LinkedStack::makeEmpty(){
LinkNode* del;
while(top != NULL){
del = top;
top = top->link;
delete del;
}
}
template
void LinkedStack::Push(const T& x){
top = new LinkNode(x, top);
assert(top != NULL);
}
template
bool LinkedStack::Pop(T& x){
if(IsEmpty() == true) return false;
LinkNode *p = top;
x = top->data;
top = top->link;
delete p;
return true;
}
template
bool LinkedStack::getTop(T& x)const{
if(IsEmpty() == true) return false;
x = top->data;
return true;
}
template
int LinkedStack::getSize()const{
LinkNode* p = top;
int k = 0;
while(p != NULL){
p = p->link;
k++;
}
return k;
}
template
std::ostream&
operator<<(std::ostream& os, LinkedStack&
s){
os<<"棧中元素的個數 =
"<<s.getSize()<<endl;
LinkNode* p = s.top;
int i = 0;
while(p != NULL){
os<<++i<<":"<<p->data<<endl;
p = p->link;
}
return os;
}
檔名:static.h
const int maxSize = 50;
template
class Stack{
public:
Stack(){};
virtual void Push(const T& x) = 0;
virtual bool Pop(T& x) = 0;
virtual bool getTop(T& x) const = 0;
virtual bool IsEmpty() const = 0;
virtual bool IsFull() const = 0;
virtual int getSize() const = 0;
};
檔名:main.cpp
#include "LinkedStack.h"
void menu(){
cout<<"1:進棧\t";
cout<<"2:退棧\t";
cout<<"3:棧頂元素\t";
cout<<"4:是否為空\t";
cout<<"5:棧中元素個數\t";
cout<<"6:清空棧中內容\t";
cout<<"7:輸出\n\r";
}
int main(){
int x;
LinkedStack linkedstack;
menu();
cin>>x;
while(1){
switch(x){
case
1:
cout<<"請輸入進棧的值:";
cin>>x;
linkedstack.Push(x);
break;
case
2:
linkedstack.Pop(x);
cout<<"退棧的數值為:"<<x<<endl;
break;
case
3:
if(linkedstack.getTop(x)){
cout<<"棧頂元素為:"<<x<<endl;
}
else{
cout<<"為空棧"<<endl;
}
break;
case
4:
if(linkedstack.IsEmpty()){
cout<<"為空"<<endl;
}
else{
cout<<"不為空"<<endl;
}
break;
case
5:
cout<<"棧中的數目為:"<<linkedstack.getSize()<<endl;
break;
case
6:
linkedstack.makeEmpty();
break;
case
7:
cout<<linkedstack;
break;
default:
break;
}
menu();
cin>>x;
}
}