gpt4 book ai didi

c++ - 调用栈打印函数时死循环

转载 作者:行者123 更新时间:2023-11-30 01:49:40 25 4
gpt4 key购买 nike

这个程序应该采用后缀算术表达式,然后编译该表达式的值。每次读取一个整数时,它都会被压入堆栈。否则,如果 +,-,* 是,则会弹出两个整数阅读。

class Stack {
Node *head;

public:
Stack() {
head = NULL;
};

void push(int data);
int pop();
bool isEmpty();
void print();
};

void Stack::push(int data)
{
Node * temp = new Node(data);
temp->next = head;
head = temp;
delete temp;
}

int Stack::pop()
{
int x = head->data;
head = head->next;
return x;
}

bool Stack::isEmpty(){
return head == NULL;
}

void Stack::print(){
Node * temp = head;
while (temp != NULL){
cout << temp->data << " ";
temp = temp->next;
}
delete temp;
}


int main() {

Stack st;
char exp [] = "23+", c;
int i, a;

for (i = 0; exp[i] != '\0'; i++){
c = exp[i];

if (c == '+'&&!st.isEmpty()){
a = st.pop() + st.pop();
st.push(a);
}
else if (c == '-'&&!st.isEmpty()){
a = st.pop() - st.pop();
st.push(a);
}
else if (c == '/'&&!st.isEmpty()){
a = st.pop() / st.pop();
st.push(a);
}
else if (c == '*'&&!st.isEmpty()){
a = st.pop() * st.pop();
st.push(a);
}
else if (c == '0')
st.push(0);
else if (c == '1')
st.push(1);
else if (c == '2')
st.push(2);
else if (c == '3')
st.push(3);
else if (c == '4')
st.push(4);
else if (c == '5')
st.push(5);
else if (c == '6')
st.push(6);
else if (c == '7')
st.push(7);
else if (c == '8')
st.push(8);
else if (c == '9')
st.push(9);

cout << c << endl;
st.print();
}
cin >> a;
return 0;
}

当我在 main 中调用 print 函数时,我得到一个无限循环作为输出。我尝试寻找导致无限循环的原因,但找不到。

最佳答案

我看到的问题:

  1. push() 中使用 delete:

    void Stack::push(int data)
    {
    Node * temp = new Node(data);
    temp->next = head;
    head = temp;
    delete temp; // This needs to go.
    }
  2. 不在 pop() 中使用 delete:

    int Stack::pop()
    {
    // Problem 1.
    // What if head is NULL?

    int x = head->data;

    // Problem 2
    // The old value of head is gone. It's a memory leak.
    head = head->next;
    return x;
    }

    你需要:

    int Stack::pop()
    {
    if ( head != NULL )
    {
    int x = head->data;
    Node * temp = head;
    head = head->next;
    delete temp;
    return x;
    }
    else
    {
    // Figure out what you want to do if head is NULL
    }
    }
  3. print() 中使用 delete

    void Stack::print(){
    Node * temp = head;
    while (temp != NULL){
    cout << temp->data << " ";
    temp = temp->next;
    }
    delete temp; // This needs to go.
    }
  4. 缺少用户定义的析构函数。您需要删除对象中的对象。否则,您正在泄漏内存。以下代码中的一些内容应该可以工作。

    Stack::~Stack()
    {
    while (head)
    {
    Node * temp = head;
    head = head->next;
    delete temp;
    }
    }

关于c++ - 调用栈打印函数时死循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28684263/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com