將整數添加到列表中可以正常工作,但是刪除和打印有問題。如何從鏈表中刪除節點?
我對調試器還不友好,但是我發現節點指針'第一個'有錯誤。它的值是-17891602。我不知道發生了什麼......
#include <iostream>
using namespace std;
class nodeList;
class node {
friend class nodeList;
private:
int data;
node* link;
public:
node() { //constructor
data = 0;
link = NULL;
}
node(int d) { //constructor
data = d;
link = NULL;
}
node(int d, node* l){ //constructor
data = d;
link = l;
}
};
class nodeList {
private:
node* first;
int num = 0;
node* nt;
public:
nodeList() {
first = new node();
}
node* end(node* t){ //return pointer of last element
t = first;
for (int i = 0; i < num; i++){
t = t->link;
}
return t;
}
void add(int a){ //add 'a' at the end of the list
node* x = new node(a);
node* y = this->end(nt);
y->link = x;
num++;
}
void del(int n){ //n : data of element that you want to delete from list
node* temp = first;
node* pretemp = NULL;
node* x;
int i;
for (i = 0; i <= this->num; i++){ //loop to find 'n'
pretemp = temp;
temp = temp->link;
if (n == temp->data){
break;
}
}
temp = first;
for (int j = 0; j<i; j++){ //i : where 'n' is,
temp = temp->link;
}
x = temp->link;
pretemp->link = x;
delete temp;
num--;
}
void printList(){
node* temp = first;
temp = temp->link;
for (int i = 0; i<this->num; i++){
cout << temp->data << endl;
temp = temp->link;
}
}
};
int main(){
nodeList *l = new nodeList();
int a;
int select;
while (1){
cout << "1. ADD 2. DELETE 3. PRINT" << endl;
cin >> select;
if (select == 1){
cout << "Enter an integer: ";
cin >> a;
if (cin.fail()) {
cout << "Wrong input" << endl;
break;
}
l->add(a);
l->printList();
}
if (select == 2){
cout << "Enter the data of the element you want to delete: ";
cin >> a;
if (cin.fail()) {
cout << "Wrong input" << endl;
break;
}
l->del(a);
l->printList();
}
if (select == 3){
l->printList();
}
}
}
那麼,用筆和紙跟蹤你的程序的預期行爲,並找出它與現實背離的地方。 –