c++实现链栈
#include<iostream>using namespace std;struct node{int data;node* next;};class Stack{private:node* top;public:Stack();~Stack();int Push(int);int Pop(int&);int isEmpty();void Clear();void Prin
·
#include<iostream>
using namespace std;
struct node{
int data;
node* next;
};
class Stack{
private:
node* top;
public:
Stack();
~Stack();
int Push(int);
int Pop(int&);
int isEmpty();
void Clear();
void Print();
};
Stack::Stack(){
top=new node;
top->data=0;
top->next=NULL;
}
Stack::~Stack(){
Clear();
}
int Stack::Push(int e){
node* tmp=new node;
tmp->data=e;
tmp->next=top;
top=tmp;
}
int Stack::Pop(int &e){
if(top==NULL)
return -1;
e=top->data;
node* tmp=top;
top=top->next;
delete tmp;
}
int Stack::isEmpty(){
return (top==NULL)?-1:0;
}
void Stack::Clear(){
node* tmp;
node* p=top;
while(p!=NULL){
tmp=p;
p=p->next;
delete p;
}
}
void Stack::Print(){
node* p=top;
while(p->next!=NULL){
cout<<p->data<<" ";
p=p->next;
}
}
int main(){
Stack s;
s.Push(11);
s.Push(22);
s.Print();
}
更多推荐
已为社区贡献2条内容
所有评论(0)