class Node{//堆栈的结点类
public:
Node();//构造函数0
Node(int x, int y, Node *p);//构造函数重载1
void get_xy(int &x, int &y);//取结点的X,Y值
void put_xy(int x, int y);//置结点的X,Y值
bool put_next(Node *n);//置结点的前驱结点域
bool put_prior(Node *p);//置结点的后继结点域
Node* get_next();//取结点的前驱结点域
Node* get_prior();//取结点的后继结点域
private:
Node *next;
Node *prior;
int point_x;
int point_y;
};
Node::Node()
{
point_x=0;
point_y=0;
next=NULL;
prior=NULL;
}
Node::Node(int x, int y, Node *p)
{
point_x=x;
point_y=y;
next=NULL;
prior=p;
}
void Node::get_xy(int &x, int &y)
{
x=point_x;
y=point_y;
}
void Node::put_xy(int x, int y)
{
point_x=x;
point_y=y;
}
bool Node::put_next(Node *n)
{
next=n;
return TURE;
}
bool Node::put_prior(Node *p)
{
prior=p;
return TURE;
}
Node* Node::get_next()
{
return next;
}
Node* Node::get_prior()
{
return prior;
}
class Stack{//链式堆栈类的实现
public:
Stack();//基本构造函数
bool push(int x, int y);//向堆栈压入新结点及数据
bool pop(int &x, int &y);//数据出栈,并销毁栈顶结点
void print_stack();//打印整个结点数据,用于调试
private:
Node base;//堆栈的栈底结点
Node *top;//堆栈的栈顶指针,注意,这里的栈顶指针指向的是栈顶的数据结点,非其上面
};
Stack::Stack():base()//堆栈的构造函数,调用结点的构造函数0
{
top=&base;
}
bool Stack::push(int x, int y)
{
if(top!=NULL)//判断结点是否存在
{
if(base.get_next()==NULL)//判断栈底结点是否有数据,注意是是否有数据,因为栈底可以为:有数据且无前驱结点;栈底无数据;栈底有数据且有前驱结点;
{
base.put_xy(x,y);
base.put_next(top);//进入循环说明属于栈底无数据且栈底结点的前驱结点为空,这里置栈底结点的前驱结点为top,使得下次复合栈底有数据且top==base,且不再入此循环
}
else
{
Node *temp=new Node(x,y,top);//建立新结点,并链接之
top->put_next(temp);
top=temp;
}
}
else
{
return FAULT;
}
return TURE;
}
bool Stack::pop(int &x, int &y)//数据出栈
{
if(base.get_next()!=NULL)//判断栈是否为空和栈底是否有数据存入
{
top->get_xy(x,y);
if(base.get_next()==top)//若符合则说明栈底有数据,且无前驱结点
{
base.put_next(NULL);
}
else//说明栈底数据不为空,且有前驱结点
{
Node *temp=top;
top=top->get_prior();
top->put_next(NULL);
delete []temp;//释放空间
}
}
else
{
return FAULT;
}
}
void Stack::print_stack()
{
Node *temp;
int x,y;
temp=&base;
while(temp!=NULL)
{
temp->get_xy(x,y);
cout<<x<<" "<<y<<" "<<endl;
temp=temp->get_next();
}
}