链栈实验(链表实现)
用链式存储实现栈
头文件
#pragma once
struct Node {
Node* next;
int data;
};
class LinkStack
{
public:
LinkStack() { top = nullptr; };//构造函数,初始化一个空栈
~LinkStack();//析构函数
void push(int x);//压栈
void pop();//弹栈
int getTop();//取栈顶元素,不弹栈
bool empty();//判断栈是否为空
private:
Node* top;//栈顶元素的指针
};
源文件
#include "LinkStack.h"
void LinkStack::push(int x) {
Node* p = new Node;//申请新结点
p->data = x;
p->next = top;//压栈
top = p;//移动栈顶指针
}
void LinkStack::pop() {
if (top == nullptr)throw"下溢";
Node* p = nullptr;
p = top;//暂存待出栈的结点
top = top->next;//移动栈顶指针(出栈)
delete p;//删除已经出栈的结点
}
int LinkStack::getTop() {
return top->data;
}
bool LinkStack::empty() {
if (top == nullptr)return true;
return false;
}
LinkStack::~LinkStack() {
Node* p = nullptr;
while (p != nullptr) {
p = top;
top = top->next;
delete p;
}
};
测试程序
#include<iostream>
using namespace std;
#include"LinkStack.h"
int main() {
LinkStack st;
cout <<"判断栈是否为空:"<< st.empty()<<endl;
//入栈三个元素
st.push(5);
st.push(2);
st.push(0);
cout << "取栈顶元素:" << st.getTop() << endl;
st.pop();
cout << "再取一次栈顶元素:" << st.getTop() << endl;
cout << "再次判断栈是否为空:" << st.empty() << endl;
}