#include <iostream>
using namespace std;
class Stack {
private:
public:
Stack() {}
virtual ~Stack() {}
virtual int pop() = 0;
virtual void push(const int& object)=0;
virtual const int& getTop()const = 0;
virtual int length()const = 0;
};
struct Node {
int elm;
Node* next;
};
class ListStack :public Stack {
private:
int count;
Node* top;
public:
ListStack();
~ListStack();
void push(const int& object);
int pop();
const int& getTop()const;
int length()const;
bool isEmpty()const;
};
ListStack::ListStack() :top(NULL), count(0) {
}
ListStack::~ListStack() {
delete[]top;
}
void ListStack::push(const int& object) {
Node* elm = new Node;
elm->elm = object;
elm->next = top;//将此时的链栈接到新节点之后
top = elm;//栈顶指向新节点
count++;//栈元素+1
}
int ListStack::pop() {
if (isEmpty()==0) {
Node* temp = top;
top= top->next;//栈顶指向栈顶下一个节点,因为要弹出栈顶元素
int elm = temp->elm;//获得弹出元素的值
delete temp;//释放删去栈顶元素
count--;
return elm;
}
else {
cout << "该栈已空" << endl;
exit(1);
}
}
const int& ListStack::getTop()const {
if (isEmpty()) {
cout << "该栈为空" << endl;
exit(1);
}
else
return top->elm;
}
int ListStack::length()const {
return count;
}
bool ListStack::isEmpty()const {
if (count == 0)
return true;
else
return false;
}
int main() {
ListStack object;
cout << "1、pop" << endl;
cout << "2、push" << endl;
cout << "3、isEmpty" << endl;
cout << "4、getTop" << endl;
cout << "5、length" << endl;
int judge;
while (1)
{
cout << "请按键" << endl;
cin >> judge;
switch (judge) {
case 1:cout<<object.pop()<<endl;
break;
case 2:cout << "请输入推入的元素" << endl;
int temp;
cin >> temp;
object.push(temp);
break;
case 3:
cout << "the answer is" << object.isEmpty() << endl;
break;
case 4:
cout << "the top is " << object.getTop() << endl;
break;
case 5:
cout << "the lengh is " << object.length() << endl;
}
}
}
链表栈的实现
最新推荐文章于 2023-10-07 17:47:05 发布