我们的家庭作业要求我们使用链表创建“Staque”(实现堆栈和队列的功能)。在列表中输入偶数时,它们应该到列表的顶部,而在底部则是奇数。因此,如果插入的值是8 1 4 6 7 9,它应该输出6 4 8 1 7 9.然后你删除前两个偶数和底部奇数将给出8 1 7.一切似乎都工作正常除非全部节点被删除,因此当您输入3个或更少的值时,程序崩溃。在这个时候,我必须完成我的任务,因为它今晚到期,但我只是想知道如何解决这个问题。任何帮助将不胜感激。
这是我的代码:
驱动:
#include <iostream>
#include "Staq.h"
using namespace std;
int main()
{
Staq *std = new Staq();
int numofvals;
int i;
int x;
cout << "How many values in the staque?" << endl;
cin >> numofvals;
cout << numofvals << " values will be entered in the staque." << endl << endl;;
for(i=1; i<=numofvals; i++)
{
cout << "Enter value " << i << ":" << endl;
cin >> x;
std->AddNode(x);
}
cout << endl;
cout << "Staque:" << endl;
std->PrintList();
std->DeleteNode();
cout << "\nStaque after deletions:" << endl;
std->PrintList();
return 0;
}
.CPP:
#include <iostream>
using namespace std;
#include "Staq.h"
Staq::Staq()
{
head = NULL;
curr = NULL;
temp = NULL;
}
void Staq::AddNode(int addData)
{
nodePtr n = new node;
n->next = NULL;
n->data = addData;
if(addData % 2 == 0)
{
if(head == NULL)
{
head = n;
curr = n;
}
else
{
n->next = head;
head = n;
}
}
else
{
if(head == NULL)
{
head = n;
curr = n;
}
else
{
temp = head;
while(temp->next != NULL)
{
temp = temp->next;
}
temp->next = n;
}
}
}
void Staq::DeleteNode()
{
nodePtr temp2 = new node;
if(head->data %2 == 0)
{
temp = head;
head = head->next;
delete temp;
if(head->data %2 == 0)
{
temp = head;
head = head->next;
delete temp;
}
}
temp = head;
while(temp->next->next != NULL)
{
temp = temp->next;
}
if(temp->data %2 != 0)
{
temp2 = temp->next;
temp->next = NULL;
delete temp2;
}
}
void Staq::PrintList()
{
curr = head;
while(curr != NULL)
{
cout << curr->data << endl;
curr = curr->next;
}
}
部首:
#include <iostream>
using namespace std;
#ifndef STAQ_H
#define STAQ_H
class Staq
{
public:
Staq();
~Staq();
void AddNode(int addData);
void DeleteNode();
void PrintList();
private:
class node
{
public:
int data;
node* next;
};
typedef class node* nodePtr;
nodePtr head;
nodePtr curr;
nodePtr temp;
};
#endif
答案 0 :(得分:1)
在DeleteNode
中,即使没有节点,您也会尝试访问第一个节点的数据。第二个节点也是如此。
while(temp->next->next)
很危险,因为temp->next
可能是NULL
,因此temp->next->next
可以访问空指针。我假设你的意思是temp->next
。您可能也想验证temp
。
最后,虽然不相关,temp2 = temp->next
会导致内存泄漏,因为现在没有人指向在DeleteNode
开头创建的新节点。