我有一个非常简单的节点类来实现链表(它只有数据和下一个指针)。下面的函数应该删除其“数据”=值的FIRST节点。该功能可以正常工作。但是当我尝试删除第一个元素(列表的头部)时,它不会。那么,问题在哪里? 下面是代码C++链表不删除头节点
class Node{
public:
int data;
Node *next;
....some other functions...
};
void deleteNode(Node *n, int value){
cout<<"after deleting node with data = "<<value<<" : ";
if(n->data == value){
n = n->next; //I guess the problem is somewhere here!
return;
}
while(n){
if(n->next->data == value){
n->next = n->next->next;
return;
}
n = n->next;
}
}
void printTheLinkedList(Node *n){
while(n){
cout<<n->data<<" --> ";
n = n->next;
}
cout<<"NULL"<<endl;
}
int main(){
Node N(0);
for(int i = 1; i < 10; i++)
N.appendNode(i);
printTheLinkedList(&N);
deleteNode(&N, 3);
printTheLinkedList(&N);
deleteNode(&N, 0);
printTheLinkedList(&N);
return 0;
}
这里是代码的输出(注:3被删除,但0不是)
0 --> 1 --> 2 --> 3 --> 4 --> 5 --> 6 --> 7 --> 8 --> 9 --> NULL
0 --> 1 --> 2 --> 4 --> 5 --> 6 --> 7 --> 8 --> 9 --> NULL
0 --> 1 --> 2 --> 4 --> 5 --> 6 --> 7 --> 8 --> 9 --> NULL
相关:让所有* *在你的链接列表中的节点动态。没有必要保持一个哨兵非动态头节点。 'nullptr'是用于推导“list-is-empty”状态的不够精确的哨兵值。 – WhozCraig