gpt4 book ai didi

c++ - 如何从链表中删除节点?

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

将整数添加到列表中工作正常,但删除和打印时出现问题。

我对调试器还不是很友好,但我发现节点指针“first”有错误。它的值为-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();
}
}
}

最佳答案

您的 del 函数删除临时节点(您需要删除的节点之前的节点)。

这是可能的解决方法:

//n : data of element that you want to delete from list
void del(int n)
{
//loop to find 'n'
for (node *tmp = first; tmp->link; tmp = tmp->link)
{
if (n == tmp->link->data)
{
node *x = tmp->link;
tmp->link = tmp->link->link;
delete x;
num--;
break;
}
}
}

此外,您的 del 是否应该删除所有具有 data == n 的节点?

关于c++ - 如何从链表中删除节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44006608/

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