我自己的Stack类进行调试

my own Stack class debugs

本文关键字:调试 自己的 Stack 我自己      更新时间:2023-10-16

我正在尝试构建自己的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;
}