正在删除单向链表中的项目
Deleting item in one way linked list
我需要一个函数,该函数根据链接列表中的项目的位置从链接列表中搜索该项目,将信息保存在变量中并删除它。例如,我想删除列表中的第五个项目,并将其内容保存到int&数字和字符串&文本"我的列表"仅在一个方向上链接。我想我已经找到了,但移除它有点困难。
private:
struct List_cell{
unsigned number;
string text;
List_cell *next;
};
List_cell *list_first_;
bool LinkedList::find_and_remove(unsigned& position, unsigned& count, unsigned& found_number, string& found_text){
List_cell *current = list_first_;
if(current == nullptr){
return false;
}
else{
while(current != nullptr){
count++;
current = current->next;
if(count == position){
found_number = current->number;
found_text = current->text;
//here should be the deleting i think
return true;
}
}
}
return false;
}
我做的每件事都正确吗?如何删除有什么建议吗?
编程引理:所有问题都可以通过额外的间接层来解决:
bool LinkedList::find_and_remove( unsigned& position,
unsigned& count,
unsigned& found_number,
string& found_text )
{
List_cell **work = &list_first_;
while(*work != nullptr) {
if ( ++count == position ) {
List_cell *tmp = *work;
*work = (*work)->next;
found_number = tmp->number;
found_test = tmp->text;
delete tmp;
return true;
}
work = &(*work)->next;
}
return false;
}
您已经找到要删除的节点,所以现在您只需要将之前的节点链接到之后的节点。因此,您需要一个指向该节点之前节点的指针。
您需要将代码修改为
if head is null, return false
initialize counter to 0
create two pointers: p as head and q as head->next
while q != null do
if counter == position do <- q is pointing to the node you need to remove
store the info from q
p->next = q->next <- this is where the node gets removed
return true
q = q->next
p = p->next
return false
或者递归:(不总是建议,但需要更少的代码)
deleteNode(head, position):
if head == null
return null
if position == 0:
return head->next
head->next = deleteNode(head->next, position - 1)
return head
您需要将节点的next
指针存储在已删除节点之前,并将其附加到已删除单元格之后的节点。
所以你需要一个以前的指针
List_cell* previous;
在你的while循环
count++;
previous = current;
current = current->next;
if(count == position){
found_number = current->number;
found_text = current->text;
previous->next = current->next;
delete current;
return true;
}
相关文章:
- 反向给定链表中的K节点
- 如果没有malloc,链表实现将失败
- 文本文件中的单词链表
- 努力将整数转换为链表。不知道我在这里做错了什么
- 链表,反向函数,数据结构
- 使用std::list创建循环链表
- 链表的泛型函数remove()与成员函数remove)
- C++ 从链表中删除项目时出现问题
- 双向链表问题 - 包含项目但不显示
- C++ 链表删除了错误的项目
- 将项目添加到双向链表的背面时遇到问题
- 无法在 C++ 中的循环中将项目添加到链表
- 当SLIST_ENTRY不是项目列表的第一个成员时,使用单向链表
- 正在删除单向链表中的项目
- 分段 删除链表的项目时出错
- 如何删除双向链表中与特定值匹配的所有项目
- 将项目添加到链表中,按引用或值传递
- 当列表中有两个以上的项目时,链表的函数 add 会崩溃
- c++如何从链表中随机挑选项目
- 作业:计算一个项目在链表中出现的次数