我自己的Stack类进行调试
my own Stack class debugs
我正在尝试构建自己的Stack类,但有一个错误,我推送了一些字符,它弹出了奇怪的字符使用链表创建和堆栈数据结构的实现
这是我的代码:
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <stdlib.h>
using namespace std;
struct node
{
char symbol;
struct node* next;
};
class Stack
{
struct node* head;
public:
Stack(){
head=NULL;
}
void push(char s)
{
if(emp()){
head=new node();
head->symbol=s;
head->next=NULL;
}
else
{
struct node* nod=new node();
nod->next=head;
nod->symbol=s;
head=nod;
free(nod);
}
}
char pop()
{
char temp=0;
if(!emp()){
struct node* p=head->next;
temp=head->symbol;
free(head);
head=p;
free(p);
return temp;
}
}
bool emp()
{
if(head==NULL)
return true;
else
return false;
}
~Stack(){while(!emp())pop();}
};
int main(int argc, char** argv)
{
Stack s;
s.push('1');
s.push('2');
cout << s.pop()<<endl;
cout << s.pop()<<endl;
return 0;
}
我推送字符"1"answers"2"流行的结果奇怪的字符!
void push(char s)
{
if(emp()){
head=new node();
head->symbol=s;
head->next=NULL;
}
else
{
struct node* nod=new node();
nod->next=head;
nod->symbol=s;
free(nod);
}
}
如果堆栈不为空,则在使用free(nod)
行将节点放在堆栈上后删除该节点。因此,当您调用pop()
时,头指向一个已删除的对象。因此,不要在push()
函数中执行任何释放或删除操作。
此外,对于使用new
关键字创建的对象,不应使用free
,而应使用delete nod;
。
pop方法看起来也有点疯狂:释放头部,然后释放堆栈中的下一个节点。试试这样的方法,只删除头对象:
char pop()
{
char tempChar = 0;
if( !emp() )
{
struct node* tempNode = head->next;
tempChar = head->symbol;
// delete the object pointed to by head
delete head;
// assign the head to the next node in the stack
head = tempNode;
}
// still need to return something even if the stack is empty
return tempChar;
}
相关文章:
- 没有为自己的结构调用列表推回方法
- 在linux上调试巨大的C++项目
- 在他自己的方法中,有可能将一个对象取消引用到另一个对象吗
- 在c++中为我自己的基于指针的数组分配内存的正确方法
- 调试编译的服务器在数据库打开时崩溃
- C++从对象自己的类中删除对象
- 使用 std::optional,而不是自己的结构
- 子轴围绕父轴而不是他自己的轴旋转
- 这个C++编译器优化(在自身的实例上调用对象自己的构造函数)的名称是什么,它是如何工作的?
- C++ 如何为自己的迭代器类从迭代器转换为const_iterator?
- 重载 + 自己的类和 std::string 的运算符
- 类无法访问自己的私有静态 constexpr 方法 - Clang bug?
- 是否可以在不填充自己的参数的情况下将模板函数作为参数传递?
- 如何访问模板参数自己的模板参数?
- G++ 切换为不包含自己的符号函数名称(和调试数据)-
- 如何在我自己的全系统模拟器上实现 GDB 调试
- 我自己的Stack类进行调试
- C++ VS 调试代码,请设置自己的调试标志
- 我的visualc++程序可以监听自己的调试输出吗?
- Visual Studio 2015调试:如何只停留在我自己的程序中