#include<iostream>
using std::cin;
using std::cout;
using std::endl;
namespace mystack2
{
typedef int type;
struct node
{
type data;
node*next;
};
class stack
{
enum{maxsize=1000};
node*head;
int items;
public:
stack();
~stack();
bool push(type x);
bool pop(type &x);
bool pop();
type top();
void fill();
void show();
};
stack::stack(){
head=new node;
head->next=NULL;
items=0;
}
stack::~stack(){
node*p;
while(head){
p=head;
head=head->next;
delete p;
}
}
bool stack::push(type x){
if(items==maxsize)
return false;
node*t=new node;
t->data=x;
t->next=head->next;
head->next=t;
items++;
return true;
}
bool stack::pop(type &x){
if(items==0)
return false;
node*p=head->next;
x=p->data;
head->next=p->next;
items--;
return true;
}
bool stack::pop(){
if(items==0)
return false;
node*p=head->next;
head->next=p->next;
items--;
return true;
}
type stack::top(){
if(items==0)
return -1;
else return head->next->data;
}
void stack::fill(){
for(int i=0;i<10;i++){
this->push(i);
}
}
void stack::show(){
node*p=head->next;
while(p){
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
}
int main()
{
using namespace mystack2;
stack one;
one.fill();
one.show();
}
c++链栈
最新推荐文章于 2025-02-18 19:53:43 发布