<分区>
我正在尝试复习数据结构并实现一个基本的链表。当我运行这段代码时,我得到以下输出:
3 4 6
1 was found and deleted 4 was found and deleted
3
4 应该删除,但显然 1 不应该删除,我想知道我的代码/逻辑中的错误在哪里。
在此先感谢您的帮助。
#include <iostream>
using namespace std;
class List {
private:
struct node {
int data;
node * next;
};
node * head;
node * curr;
node * temp;
public:
List();
void addNode(int newData);
void deleteNode(int delData);
void printList();
};
int main() {
List test;
test.addNode(3);
test.addNode(4);
test.addNode(6);
test.printList();
cout << endl << endl;
test.deleteNode(1);
test.deleteNode(4);
cout << endl << endl;
test.printList();
}
List::List(){
head = NULL;
curr = NULL;
temp = NULL;
}
void List::addNode(int newData){
node * n = new node;
n->next = NULL;
n->data = newData;
if (head != NULL) { // List is intact
curr = head; // if List is not empty, make curr equal to the head, and start at the beginning of the list.
while(curr->next != NULL) { // Get to last item on the list
curr = curr->next;
}
curr->next = n; // Use the last item, and point to the new node.
}
else { // empty list
head = n; // new node is the head of the list.
}
}
void List::deleteNode(int delData){
node * n = new node;
temp = head;
curr = head;
if (head != NULL) {
while (curr->next != NULL && curr->data != delData) {
temp = curr;
curr = curr->next;
}
if (curr == NULL) {
cout << delData << " was not found in the list\n";
delete n;
}
else {
n = curr;
curr = curr->next;
temp->next = curr;
delete n;
cout << delData << " was found and deleted\n";
}
}
}
void List::printList(){
curr = head;
while (curr != NULL) {
cout << curr->data << endl;
curr = curr->next;
}
}