【发布时间】:2015-03-02 06:23:44
【问题描述】:
抱歉,这是一个相当长的问题...我正在为队列的链表实现创建一个特定的函数。这个函数叫做int Queue::modify(int item),它接受一个整数,如果这个整数出现在队列中不止一次,我必须从队列中删除所有出现的整数,除了第一个。
例如,如果我的队列看起来像 [1,2,2,2,2,2,3] 并且项目是 2,则生成的队列看起来像 [1,2,3]。但是,我的代码正在输出 [1,2,2,2,3]。
下面是我的代码,下面是我对如何尝试实现此功能的解释:
int Queue::modify(int item){
node* curr = front;
node* temp;
int counter = 0;
if (curr == NULL){
return 0;
}
//checking to see if first instance of queue is == item
if (curr->data == item){
counter++;
}
//checking to see if instances after first instance of queue is == item
while (curr != NULL){
if (curr->next != NULL){
temp = curr->next;
if (temp->data == item){
counter ++;
if (counter > 1){
if (curr->next->next != NULL){
curr->next = curr->next->next; //I think something is wrong here??
}
delete temp;
}
}
curr = curr->next;
}
//this is for the last instance of the queue, so curr->next == NULL
else{
if (curr->data == item){
counter++;
if (counter > 1){
delete curr;
curr = NULL;
}
else
curr = curr->next; //so curr should be NULL now
}
else
curr = curr->next; //so curr should be NULL now
}
}
return counter;
}
所以基本上,我尝试的是拥有temp = curr->next,这样如果curr->next->data == item,那么我可以让curr的下一个指针指向temp之后的节点,这样列表仍然是链接的curr->next = curr->next->next,然后删除temp如下图所示:
我感觉我在放屁,curr->next = curr->next->next 不正确...提前感谢您对我的代码有什么问题提出的任何建议!另外,这是家庭作业,所以虽然我绝对喜欢完整的代码解决方案,但请不要发布完整的代码解决方案......谢谢! :D
【问题讨论】: