如何删除链接列表中的节点?
这是我迄今为止,但它不是在测试文件上工作。基本上跳到别的if(cnode == preposition)
如何删除链接列表中的节点?
void LinkedList::Delete(Node *PrePosition) { Node *cnode = head;
Node *pnode = NULL;
while (cnode != NULL) {
if (cnode->value != NULL) {
if (pnode == NULL) {
//if there is not previous node
head = cnode->next;
}
else if(cnode == PrePosition){
//if there is previous node
cout << endl << "Deleting: " << cnode << endl;
pnode->next = cnode->next;
}
}
else {
//dont delete
pnode = cnode;
}
cnode = cnode->next;
}
}
回答:
1:从以前的节点带指针,它指向要删除
2一前一后的下一个:从以前的节点删除指针当前节点
3:删除从下一个节点的指针到当前节点(如果它是一个双向链表)
回答:
三起案件在单链表中删除的:
从codementor删除第一个节点
void delete_first()
{
node *temp=new node;
temp=head;
head=head->next;
delete temp;
}
删除最后一个节点
void delete_last()
{
node *current = new node;
node *previous = new node;
current=head;
while(current->next != NULL)
{
previous = current;
current = current->next;
}
tail = previous; // if you have a Node* tail member in your LinkedList
previous->next = NULL;
delete current;
}
删除在特定的位置(你的情况)
void LinkedList::delete_position(int pos)
{
node *current=new node;
node *previous=new node;
current=head;
for(int i=1; i < pos; i++) //or i = 0; i < pos-1
{
previous=current;
current=current->next;
}
previous->next=current->next;
}
^^ ^^
但是,如果你的函数签名打算delete_node(Node* nodeToDelete)
[介词是不是一个好名字在这种情况下]你想删除传递给函数的节点在不知道我们可以修改delete_position(在列表中的位置),像这样:
void LinkedList::delete_node(Node* nodeToDelete) {
if (head == nodeToDelete){
head = nodeToDelete->next;
return
}//else:
node *current=new node;
node *previous=new node;
current=head;
while(current != nodeToDelete)
{
previous = current;
current = current->next
}
previous->next = current->next;
}
另外在你的原代码,如果它跳过你所提到的线,pnode总是空当cnode中有一个非空值。
以上是 如何删除链接列表中的节点? 的全部内容, 来源链接: utcz.com/qa/257175.html