编译正常但在执行时我得到分段错误(核心转储)错误。我已经单独测试了每个功能,并且添加功能是唯一一个给我这个错误的功能。添加函数应该将值添加到链表的头部。运行代码时,值会正确添加到列表中,我可以显示列表,但错误发生在不久之后。非常感谢任何帮助!
//Homework 11
//Linked List
#include <iostream>
using namespace std;
//Declaring class and Linked List.
class NumberList
{
private:
struct ListNode
{
double value;
struct ListNode *next;
};
ListNode *head;
public:
NumberList()
{ head = NULL;}
~NumberList()
{
ListNode *nodePtr;
ListNode *nextNode;
nodePtr = head;
while (nodePtr != NULL)
{
nextNode = nodePtr->next;
delete nodePtr;
nodePtr = nextNode;
}
}
//Function inserting node at the head.
void add(double x)
{
ListNode *newNode;
ListNode *nodePtr;
ListNode *previousNode = NULL;
newNode = new ListNode;
newNode->value = x;
if (!head)
{
head = newNode;
newNode -> next = NULL;
}
else
{
nodePtr = head;
previousNode = NULL;
}
if (previousNode == NULL)
{
head = newNode;
newNode->next = nodePtr;
}
}
//Function to find matching values.
bool isMember(double x)
{
int pos = 0;
bool flag = false;
if (head == NULL)
{
cout << "List is Empty" << endl;
return flag;
}
ListNode *nodePtr;
nodePtr = head;
while (nodePtr != NULL)
{
pos++;
if (nodePtr->value == x)
{
flag = true;
cout << x << " was found at position " << pos << endl;
}
nodePtr = nodePtr->next;
}
if (!flag)
{
cout << x << " not found in the list." << endl;
}
return flag;
}
//Function to display linked list values.
void display() const
{
ListNode *nodePtr;
if (head == NULL)
{
cout << "List is empty." << endl;
return;
}
nodePtr = head;
cout << "The list goes: " << endl;
while (nodePtr != NULL)
{
cout << nodePtr->value << endl;
nodePtr = nodePtr->next;
}
cout << "End" << endl;
}
//Function to delete a selected value in the list.
void deletNodeAll(double x1)
{
ListNode *nodePtr;
ListNode *previousNode;
if (!head)
return;
if (head->value == x1)
{
nodePtr = head->next;
delete head;
head = nodePtr;
}
else
{
nodePtr = head;
while ( nodePtr != NULL && nodePtr->value != x1)
{
previousNode = nodePtr;
nodePtr = nodePtr->next;
}
if (nodePtr)
{
previousNode->next = nodePtr->next;
delete nodePtr;
}
}
}
};
int main()
{
NumberList Z;
Z.add(3);
Z.add(4);
Z.add(2);
Z.add(5);
Z.add(7);
Z.add(4);
Z.add(7);
Z.add(5);
Z.add(2);
Z.display();
Z.isMember(2);
Z.deletNodeAll(2);
Z.display();
return 0;
}
答案 0 :(得分:0)
您的add()
方法导致细分错误,因为对于第一个节点,您应该更新head
和head->next
以及return
,但您没有。
if (!head) {
head = newNode;
newNode -> next = NULL;
return ;/* do this else this again check previousNode == NULL also
which is not needed 1st time */
}
此外deletNodeAll()
仅删除您传递的第一个号码,逻辑中存在错误,请自行检查。