我正在尝试使用单链表在c ++中实现堆栈,但是遇到了一些问题。推送工作正常,但弹出菜单删除了顶部,但无法更新到下一个。另外,打印功能正在获取读取访问冲突异常。任何帮助将不胜感激!
#include <iostream>
using namespace std;
template <class T>
class node {
public:
T data;
node<T>* next;
};
template <class T>
class Stack {
private:
node<T>* top;
public:
Stack() {
top = nullptr;
}
bool isEmpty() {
if (top == nullptr)
return false;
else
return true;
}
T Top() {
if (top)
return top->data;
else
cout << "Stack is empty" << endl;
}
void push(const T & val) {
if (top == nullptr) {
top = new node<T>;
top->next = nullptr;
top->data = val;
}
else {
node<T>* temp = new node<T>;
temp->data = val;
top->next = temp;
top = temp;
}
}
void pop() {
if (top == nullptr) {
cout << "Stack is empty" << endl;
return;
}
else {
cout << top->data << " is popped" << endl;
node<T>* temp = top;
top = top->next;
delete temp;
}
}
void print() {
node<T>* temp = top;
while (temp != nullptr)
{
cout << temp->data << " ";
temp = temp->next;
}
}
};
测试堆栈类的主要功能
int main()
{
Stack<int> s;
bool flag = true;
while (flag)
{
cout << "1. Push 2. Pop 3. Print 4. Quit" << endl;
int choice;
cin >> choice;
switch (choice) {
case(1):
cout << "Enter a number to push in Stack?";
int n;
cin >> n;
s.push(n);
break;
case(2):
s.pop();
break;
case(3):
s.print();
break;
case(4):
cout << "Quitting program........." << endl;
return 1;
default:
cout << "Invalid choice!!" << endl;
break;
}
}
return 0;
}