C ++中的链接列表队列

时间:2015-03-02 06:23:45

标签: c++ queue

我很抱歉这是一个相当长的问题......我正在为队列的链表实现创建一个特定的函数。这个函数叫做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之后的节点,这样列表仍然是链接的,{{1} },然后删除temp,如下图所示:

enter image description here

我有一种感觉,我大脑放屁,curr->next = curr->next->next不正确...提前感谢您对我的代码有什么问题的任何建议!此外,这个 IS HOMEWORK 所以尽管我非常喜欢完整的代码解决方案,但请不要发布完整的代码解决方案....谢谢! :D

2 个答案:

答案 0 :(得分:1)

在这些行中,

if (counter > 1){
    if (curr->next->next != NULL){
        curr->next = curr->next->next; //I think something is wrong here??
    }

您正在跳过节点。周围的代码必须是:

if (temp->data == item)
{
    counter ++;
    if (counter > 1){
       curr = temp->next;
       delete temp;
    }               
}
else
{
   curr = curr->next;
}

答案 1 :(得分:1)

我想,那个条件

if (curr->next->next != NULL){

不需要。你可以复制

curr->next = curr->next->next; 

无论如何

相关问题