您的位置:首页 > 其它

实验三、链栈

2017-10-16 16:47 211 查看
用单链表的头部作为栈顶
入栈操作:申请一个结点,将结点插入栈顶
出栈操作:暂存栈顶元素,将栈顶结点摘链
#include
using namespace std;
struct Node
{
int data;
Node *next;
};
class linkstack
{
public:
linkstack() { top = NULL; }
~linkstack() {};
void push(int x);
int pop();
void print();
int gettop() { if (top != NULL)return top->data; }
int empty() { return(top == NULL) ? 1 : 0; }
private:
Node *top;
};
void linkstack::push(int x)
{
Node *s;
s = new Node;
s->data = x;
s->next = top;
top = s;
}
int linkstack::pop()
{
if (top == NULL)throw"下溢";
int x = top->data;
Node *p;
p = top;
top = top->next;
delete p;
return x;
}
void linkstack::print()
{
Node *p;
p = top;
while (p != NULL)
{
cout << p->data;
p = p->next;
}
}
int main()
{
linkstack a;
a.push(6);
a.print();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: