我很抱歉,这是一个相当长的问题......我正在为一个队列的链表实现一个特定的函数。这个函数被称为int Queue::modify(int item)
,它取整数,如果这个整数在队列中多次出现,我必须从队列中除去第一个整数。C++中的链表队列
因此,例如,如果我的队列看起来像[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的下一个指针指向温度后的节点,使得列表中仍然连接,curr->next = curr->next->next
,然后删除临时如下面的奇妙所示图中:
我有一种感觉,我是脑部放屁,curr->next = curr->next->next
是不正确的...先谢谢你对我的代码有什么问题的任何建议!另外,这个是家庭版所以尽管我绝对会喜欢一个完整的代码解决方案,请不要发布完整的代码解决方案....谢谢! :d
谢谢你的建议,任何情况下!我试着改变我的代码,但不幸的是,我得到了一个分段错误...猜测我的代码比我想象的要慢......我会尽量调整我的代码,并回复你! – user3362107 2015-03-02 07:03:27