如何在不向类函数传递任何参数的情况下从单个链表中删除节点(两个节点之间)?
例如,我有一个包含 6 个节点和一个头节点的列表,我想从类函数中删除其中两个(事先不知道它们的地址或位置),我该怎么做?
void WordList::deleteNode(){
Node *temp;
temp=head;
if(temp->count<=10)
{
//delete this node... not sure how though
}
else
temp=temp->next;
}
其中 WordList 是我的类,Node 是我的结构,它包含一个单词、一个计数和一个指针。 我想删除计数器等于或小于 10 的任何节点。
最佳答案
您的编辑有先验信息,表示“counter <= 10”:-)
用于删除单链表中满足该条件的元素的伪代码:
def delLessThanTen:
# Delete heads meeting criteria, stop when list empty.
while head != NULL and head->count <= 10:
temp = head->next
free head
head = temp
if head == NULL:
return
# Head exists, with count > 10, process starting there (we check
# NEXT element for criteria then delete if met).
ptr = head
while ptr->next != NULL:
# If next in list meets criteria, delete it, otherwise advance.
if ptr->next->count <= 10:
temp = ptr->next->next
free ptr->next
ptr->next = temp
else:
ptr = ptr->next
return
关于c++ - 如何从链表中删除节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3732399/