在 C++ 中使用链表进行堆栈
stack using linked lists in c++
>任何人都可以帮助我解决我遇到的这个小问题吗? 我正在尝试使用 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
的复制赋值运算符(如果你不想编写最后两个,可以删除它们(。
相关文章:
- 在 C++ 中使用链表进行堆栈
- 实现基于链表的堆栈的基于范围的 for 循环
- 使用带有链表的堆栈数据结构将中缀转换为后缀
- 使用链表在 c++ 中堆栈嵌入
- 使用链表实现堆栈时出错
- 未分配被释放的指针(将堆栈实现为链表时)
- 在C++中使用链表的堆栈实现中,访问结构体headNode成员count和top会导致运行时错误
- 双链表堆栈删除函数不起作用
- 使用链表在堆栈中插入和删除
- C++ 中堆栈的链表实现
- c++ 中 if 语句中的多个条件(通过链表实现堆栈)
- 链表堆栈头文件中"<"标记之前的预期初始值设定项
- 链表与动态数组用于使用向量类实现堆栈
- 使用链表C++堆栈
- 链表堆栈类的复制构造函数:我的正在向后复制
- 尝试创建链表堆栈时出现链接器错误
- 学习在C++中实现链表堆栈类
- 反转使用链表实现的堆栈
- 菜单驱动的程序,堆栈为带字符信息的链表
- 需要修改堆栈/链表程序以确定单词是否为回文