gpt4 book ai didi

c++ - 单链表不工作(C++)

转载 作者:搜寻专家 更新时间:2023-10-31 01:34:13 25 4
gpt4 key购买 nike

以下代码构建正确,但在我运行时导致程序崩溃。有人可以告诉我它有什么问题吗?我怀疑 DeleteNode 函数有问题。

#include <iostream>
#include <cstdlib>

using namespace std;

class list {
private:
typedef struct node {
int data;
node* next;
}* nodePtr; //this means that 'nodePtr' will mean a pointer to the struct node

nodePtr head;
nodePtr current;
nodePtr temp;

public:
list() { //constuctor
head = NULL;
current = NULL;
temp = NULL;
};

void AddNode(int addData) //to add a particular data value
{
nodePtr n= new node;
n->next = NULL;
n->data = addData;

if (head != NULL) { //if a list is already set up
current = head;
while (current->next != NULL) { //to get to the last node in the list
current = current->next;
}
current->next = n;
}
else { // if list is not created
head = n; //new node is front of the list
}
}

void DeleteNode(int delData) //to delete a particular data value
{
nodePtr delPtr = NULL;
temp = head;
current = head;

while (current != NULL && current->data!=delData) { //pass through whole list && find value
temp = current;
current = current->next;
}

if (current = NULL) { //data value not found in list
cout << delData << " was not in the list." << endl;
delete delPtr; //to free up memory space
}
else {
delPtr = current;
current = current->next;
temp->next = current; //to reconnect list

if (delPtr == head) {
head = head->next;
temp = head;
}

delete delPtr;
cout << "The value " << delData << "was deleted." << endl;
}
}

void PrintList() //to print all the data values
{
current = head;

while (current != NULL) { //to go through the data valued of the list
cout << current->data << endl;
current = current->next;
}
}

};



int main()
{
list Shahzad;

Shahzad.AddNode(2);
Shahzad.AddNode(78);
Shahzad.AddNode(28);
Shahzad.AddNode(2398);

Shahzad.DeleteNode(78);
Shahzad.PrintList();
return 0;
}

最佳答案

您的第一个问题是以下行:

if (current = NULL)

此时您实际上是分配 nullcurrent

这实际上应该是:

if (current == NULL)

关于c++ - 单链表不工作(C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40027226/

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