【发布时间】:2014-02-17 01:31:35
【问题描述】:
我有一个非常简单的节点类来实现链表(它只有数据和下一个指针)。下面的函数应该删除具有“数据”=值的第一个节点。 该功能工作正常。但是当我尝试删除第一个元素(列表的头部)时,它没有。那么,问题出在哪里? 这是代码
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是一个非常好的标记值,用于推断“列表为空”状态。
标签: c++ linked-list