gpt4 book ai didi

C++ - 模板类堆栈实现中的反向函数

转载 作者:太空宇宙 更新时间:2023-11-04 11:31:13 24 4
gpt4 key购买 nike

这是我使用带有结构类型节点和类类型堆栈的模板的堆栈实现:


堆栈.h

#ifndef STACK_H_
#define STACK_H_

#include <cstdlib>
#include <iostream>
#include <cassert>

using namespace std;

template <class t>
struct node{
t data;
node<t>* next;
};

template <class t>
class stack
{
public:
stack();
~stack();
bool isEmpty(){ return (top_ptr=NULL);};
void push(const t&);
void pop();
t top() const;
void reverse();
void clear();
void print();
private:
node<t>* top_ptr;
};

template <class t>
stack<t>::stack()
{
top_ptr=NULL;
}

template <class t>
stack<t>::~stack()
{
while(top_ptr != NULL) pop();
}

template <class t>
void stack<t>::push(const t& source)
{
node<t>* new_node = new node<t>;
new_node->data = source;
new_node->next = top_ptr;
top_ptr = new_node;
cout << "Inserito!" << endl;
}

template <class t>
void stack<t>::pop()
{
node<t>* remove = top_ptr;
top_ptr = top_ptr->next;
delete remove;
cout << "Rimosso!" << endl;
}

template <class t>
t stack<t>::top() const
{
assert(top_ptr != NULL);
return top_ptr->data;
}

template <class t>
void stack<t>::clear()
{
node<t>* temp;
while(top_ptr != NULL)
{
temp = top_ptr;
top_ptr = top_ptr->next;
delete temp;
}
cout << "Clear completato!" << endl;
}

template <class t>
void stack<t>::reverse()
{
stack<t> new_stack;
while(top_ptr != NULL)
{
new_stack.push(top_ptr->data);
pop();
}
cout << "Reverse completato!" << endl;
}

template <class t>
void stack<t>::print()
{
node<t>* ptr = top_ptr;
while(ptr!=NULL)
{
cout << " " << ptr->data << endl;
ptr = ptr->next;
}
}

#endif /* STACK_H_ */


这是 main.cpp:

#include "stack.h"

int main()
{
stack<int> stackino;
for(int i = 0; i<10; i++) stackino.push(i);
stackino.pop();
cout << "top(): " << stackino.top() << endl;
stackino.print();
cout << "Invoco clear()" << endl;
stackino.clear();
cout << "Stackino dopo clear():" << endl;
stackino.print();
cout << "Invoco reverse()" << endl;
stackino.reverse();
cout << "Stackino dopo reverse()" << endl;
stackino.print();

cout << "FINE!" << endl;
return 0;
}


问题是 reverse() 导致程序崩溃,我猜“top_ptr = new_stack.top_ptr”是错误的但它编译和执行,但崩溃。有人可以帮我改正吗?

最佳答案

我想我理解了这个问题。如果我解释错了,请告诉我。当您执行 top_ptr = new_stack.top_ptr 时,您将把临时堆栈的顶部作为您的。问题是,当那个临时堆栈被破坏时,它仍然有相同的 top_ptr,并删除所有与之关联的内存。这会使您的真实堆栈出现错误的 top_ptr

我建议尝试:

top_ptr = new_stack.top_ptr;
new_stack.top_ptr = NULL;

这样它就不会清除您的堆栈,并给您留下一个错误的指针。希望有用吗?

关于C++ - 模板类堆栈实现中的反向函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24688014/

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