栈的链式存储—C++实现
栈的链式存储类似于单链表的链式存储,头指针就相当于指向栈顶结点的指针。相当于只能操作单链表的头部,操作有:入栈、出栈、判断是否为空、获取栈顶结点的数据。
头文件如下:
#include<iostream>
using namespace std;
class StackNode
{
public:
int data;
StackNode* next;//指向下一个结点的指针
};
class LinkStack
{
public:
LinkStack();
~LinkStack();
void Push(int x);//入栈
int Pop();//出栈
int GetTop();//获取栈顶元素
bool Isempty();//判断是否为空
private:
StackNode* top;//指向栈顶结点
};
具体实现如下:
#include<iostream>
#include"栈的链式存储.h"
using namespace std;
LinkStack::LinkStack()
{
this->top = NULL;
}
LinkStack::~LinkStack()
{
StackNode* p;
while (top != NULL)
{
p = top;
top = top->next;
delete p;
}
}
void LinkStack::Push(int x)//入栈
{
StackNode* s = new StackNode;
s->data = x;
s->next = top;
top = s;
}
int LinkStack::Pop()//出栈
{
if (Isempty())
cout << "空栈出啥呀" << endl;
else
{
StackNode* n;
int x;
x = top->data;
n = top;
top = top->next;
delete n;
return x;
}
}
int LinkStack::GetTop()//获取栈顶元素
{
if (top != NULL)
return top->data;
}
bool LinkStack::Isempty()
{
if (top == NULL)
return true;
else return false;
}
int main()
{
LinkStack ls;
ls.Push(1998);
ls.Push(1997);
ls.Push(1996);
bool ret=ls.Isempty();
if (ret)
cout << "空栈" << endl;
else
cout << "非空栈" << endl;
int temp=ls.GetTop();
cout << "当前栈顶元素为:" << temp << endl;
int num=ls.Pop();
cout << "被删除的元素为:" << num << endl;
temp=ls.GetTop();
cout << "当前栈顶元素为:" << temp << endl;
}
输出结果如下:
值得注意的部分:
入栈时,我们之前写单链表时,head指向的是空,head->next指向的才是第一个结点。对应栈中head->next其实就是指向栈顶元素的指针。带入头插模板即可。