以下代碼可以正確構建,但會導致程序在運行時崩潰。有人可以告訴我它有什麼問題嗎?我懷疑DeleteNode函數有問題。單鏈表無法正常工作(C++)
#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;
}
歡迎來到Stack Overflow!這聽起來像你可能需要學習如何使用調試器來遍歷代碼。使用一個好的調試器,您可以逐行執行您的程序,並查看它與您期望的偏離的位置。如果你打算做任何編程,這是一個重要的工具。進一步閱讀:** [如何調試小程序](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/)** – NathanOliver
解決此類問題的正確工具是您的調試器。在*堆棧溢出問題之前,您應該逐行執行您的代碼。如需更多幫助,請閱讀[如何調試小程序(由Eric Lippert撰寫)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。至少,您應該\編輯您的問題,以包含一個[最小,完整和可驗證](http://stackoverflow.com/help/mcve)示例,該示例再現了您的問題,以及您在調試器。 –
我沒有讀全部,但'if(current = NULL)'不能很好 – RyanP