在 C++ 中使用链表进行堆栈

stack using linked lists in c++

本文关键字:堆栈 链表 C++      更新时间:2023-10-16

>任何人都可以帮助我解决我遇到的这个小问题吗? 我正在尝试使用 c++ 中的链表实现堆栈。 当我进入 end 时,程序应该显示堆栈的元素,但程序只是输出我输入的最后一个元素,每当我输入 pop 时,程序都会忽略我的第一个推送元素。 程序应通过来自搁浅输入的命令推送和弹出,例如(推送 2、推送 1、弹出、窥视或结束( 任何帮助将不胜感激。

#include <iostream>
#include <string>
#include <limits>
using namespace std;
class Stack
{
private:
struct node
{
int data;
node* next;
};
public:
node* top;
Stack()
{
top = NULL;
}
void push(int n)
{
node* temp = new node;
temp->data = n;
temp->next = NULL;
top = temp;
}
int pop()
{
node* temp = top;
top = top->next;
return temp->data;
}
int peek()
{
return top-> data;
}
bool isEmpty()
{
return top == NULL;
}
};
int main()
{
Stack stack;
std::string command;
while (true)
{
std::cout << "stack>";
std::cin >> command;
try
{
if (command == "pop")
{
if (stack.isEmpty())
{
throw std::runtime_error("error: stack is empty");
}
std::cout << stack.pop() << std::endl;
}
else if (command == "push")
{
int n;
if (!(std::cin >> n))
{
throw std::runtime_error("error: not a number");
}
stack.push(n);
}
else if (command == "peek")
{
if (stack.isEmpty())
{
throw std::runtime_error("error: stack is empty");
}
std::cout << stack.peek() << std::endl;
}
else if (command == "end")
{
while (!(stack.isEmpty()))
{
std::cout << stack.pop() << std::endl;
}
return 0;
}
else
{
throw std::runtime_error("error: invalid command");
}
}
catch (std::runtime_error& e)
{
std::cin.clear();
std::cin.ignore(numeric_limits<streamsize>::max(), 'n');
std::cerr << std::endl << e.what() << std::endl;
}
}
return 0;
}

你的问题出在push

void push(int n)
{
node* temp = new node;
temp->data = n;
temp->next = NULL;
top = temp;  // At this point, you have forgotten about the old value of top
}

它应该是:

void push(int n)
{
node* temp = new node;
temp->data = n;
temp->next = top; // Link rest of stack in
top = temp; 
}

你在pop中还有一个内存泄漏,你需要一个析构函数、一个复制构造函数和一个stack的复制赋值运算符(如果你不想编写最后两个,可以删除它们(。