数据结构菜鸟问题

来源:百度知道 编辑:UC知道 时间:2024/09/28 08:49:09
下面是我编的一个有关数据结构的简单程序,运行时发现内存报错.
#include <iostream>
using namespace std;
//define elementtype int;
struct Node
{
int data;
Node *next;
};
class stack
{
private:
Node *head;
public:
stack()
{
head=new Node;
head->next=NULL;
}
void push(int x);
bool empty()const;
int pop();
~stack()
{
Node *u;
while (head!=NULL)
{
u=head;
head=head->next;
delete u;
}
}
};
void stack::push(int x)
{
Node *temp1=new Node;
Node *temp2=head;
temp1->data=x;
temp1->next=temp2->next;
temp2->next=temp1;
}
int stack::pop()
{
Node *temp=head->next;
int tempint;
if (empty())
{
cout<<"the stack is empty!"<<endl;
exit(0);
}
else
while (temp->next!=

最原始的代码好像是个队列,先进先出。。。。,并不是stack,修改了一下,问题出在函数pop的时候没有将最后的指针只向NULL,你delete最后一个Node的时候,应该将他的前一个指针的next指向NULL,应为你delete了最后一个Node,并不会将最后一个节点的内容置NULL,第二次 POP的时候,你delete的仍然是原始的最后一个节点,double delete 。
具体改法如下:

#include <iostream>
using namespace std;
//define elementtype int;
struct Node
{
int data;
Node *next;
};
class stack
{
private:
Node *head;
public:
stack()
{
head=new Node;
head->next=NULL;
}
void push(int x);
bool empty()const;
int pop();
~stack()
{
Node *u=head;
Node* temp;
while (u != NULL)
{
temp= u;
u=u->next;
delete temp;
}
}
};

void stack::push(int x)
{
Node *temp1=new Node;
Node *temp2=head;
temp1->data=x;
temp1->next=temp2->next;
temp2->next=temp1;
}
int stack::pop()
{
int tempint;