gpt4 book ai didi

c++ - 双链表 - 不能删除第一个节点

转载 作者:行者123 更新时间:2023-11-30 04:58:07 27 4
gpt4 key购买 nike

 struct Node
{
int data;
Node *next;
Node *prev;
};

class DoublyLinkedList
{
ofstream cout3;
Node *head;
public:
DoublyLinkedList()
{
head = NULL;
cout3.open("task3.out");
}

void insert(int num)
{
Node *temp = new Node;
//To insert if there are no elements
if(head == NULL)
{
temp->prev = NULL;
temp->data = num;
temp->next = NULL;
head = temp;
}
//To insert if there are elements
else
{
temp->prev = NULL;
temp->data = num;
temp->next = head;
head->prev = temp;
head = temp;
}
cout3<<"inserted "<<num<<endl;
}

void dele(int num)
{
Node *temp = head;
int found_num = 0;
while(temp != NULL)
{
if(temp->data == num)
{
found_num = 1;
break;
}
else
temp = temp->next;
}
if(found_num == 0)
cout3<<"cannot delete "<<num<<endl;
//To delete first element
else if (temp->prev == NULL)
{
head = temp->next;
(temp->next)->prev == NULL;
delete temp;
cout3<<"deleted "<<num<<endl;
}
//To delete last element
else if (temp->next == NULL)
{
(temp->prev)->next = NULL;
cout3<<"deleted "<<num<<endl;
delete temp;
}
//To delete any other element
else
{
(temp->prev)->next = temp->next;
(temp->next)->prev = temp->prev;
cout3<<"deleted "<<num<<endl;
delete temp;
}
}

void search(int num)
{
Node *temp = head;
int found_num = 0;
while(temp != NULL)
{
if(temp->data == num)
{
found_num = 1;
break;
}
else
temp = temp->next;
}
if(found_num == 0)
cout3<<"not found "<<num<<endl;
else
cout3<<"found "<<num<<endl;
}

void display()
{
Node *temp = head;
while(temp != NULL)
{
cout3<<temp->data<<" ";
temp = temp->next;
}
cout3<<endl;
}
};

我的双向链表实现。我只在开头插入并删除第一次出现的数字。但是,如果我想删除第一个元素,那么它会打印“已删除 number”,但是当我显示该数字时,它仍然存在。问题似乎出在我的删除功能上,但我找不到它是什么

最佳答案

看到这一行:(temp->next)->prev == NULL;你写了 == 而不是 = ,这似乎是问题所在。您没有显示如何打印该值,但我猜您在开始之前向后移动直到空值..

关于c++ - 双链表 - 不能删除第一个节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51797926/

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