我正在尝试构建自己的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'和'2' pop的结果很奇怪!
答案 0 :(得分:0)
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()
时,head指向已删除的对象。因此,请勿在{{1}}函数中执行任何释放或删除操作。
此外,您不应将[{1}}用于使用push()
关键字使用free
创建的对象。
pop方法看起来有点疯狂:你释放头部,然后释放堆栈中的下一个节点。尝试这样的事情,你只删除头部对象:
new