【问题标题】:Linked List Queue in C++C++中的链表队列
【发布时间】: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

【问题讨论】:

    标签: c++ queue


    【解决方案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;
    }
    

    【讨论】:

    • 感谢您的建议!我尝试更改该部分的代码,但不幸的是,我遇到了分段错误……我猜我的代码比我想象的要错误……我会尝试更多地调整我的代码并回复您!
    【解决方案2】:

    我想,那个条件

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

    不需要。你可以复制

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

    无论如何

    【讨论】:

    • 没问题。有时好问题几乎是一个答案。祝你好运!
    猜你喜欢
    • 1970-01-01
    • 2011-06-28
    • 2021-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多