C++ 在c+中使用链表进行堆栈+;
谁能帮我解决这个小问题? 我尝试用C++实现一个使用链表的堆栈。 当我输入end时,程序应该显示堆栈的元素,但程序只是输出我输入的最后一个元素,每当我输入pop时,程序都忽略我的第一个推送元素。 程序应通过来自绞合输入的命令进行推送和弹出,例如(推2、推1、弹出、peek或end) 任何帮助都将不胜感激C++ 在c+中使用链表进行堆栈+;,c++,linked-list,C++,Linked List,谁能帮我解决这个小问题? 我尝试用C++实现一个使用链表的堆栈。 当我输入end时,程序应该显示堆栈的元素,但程序只是输出我输入的最后一个元素,每当我输入pop时,程序都忽略我的第一个推送元素。 程序应通过来自绞合输入的命令进行推送和弹出,例如(推2、推1、弹出、peek或end) 任何帮助都将不胜感激 #include <iostream> #include <string> #include <limits> using namespace std; c
#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;
}
#包括
#包括
#包括
使用名称空间std;
类堆栈
{
私人:
结构节点
{
int数据;
节点*下一步;
};
公众:
节点*顶部;
堆栈()
{
top=NULL;
}
无效推送(整数n)
{
node*temp=新节点;
温度->数据=n;
temp->next=NULL;
顶部=温度;
}
int-pop()
{
节点*温度=顶部;
顶部=顶部->下一步;
返回温度->数据;
}
int peek()
{
返回top->data;
}
布尔是空的
{
返回top==NULL;
}
};
int main()
{
堆叠;
std::string命令;
while(true)
{
std::cout>命令;
尝试
{
如果(命令==“pop”)
{
if(stack.isEmpty())
{
抛出std::runtime_错误(“错误:堆栈为空”);
}
标准:cout n)
{
抛出std::runtime_错误(“错误:不是数字”);
}
堆栈推送(n);
}
else if(命令==“peek”)
{
if(stack.isEmpty())
{
抛出std::runtime_错误(“错误:堆栈为空”);
}
std::cout您的问题在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
中也存在内存泄漏,并且在堆栈中需要析构函数、复制构造函数和复制赋值运算符(如果不想编写,可以删除最后两个)不相关,但每次你在代码> POP<代码>时都会漏掉节点。C++没有垃圾收集,你需要<代码>删除< /代码>你的代码>新< /COD>。在任何时候,你都不能设置一个节点的代码<下一个>代码>,而不是<代码> null < /C>。