首页 \ 问答 \ 带链接列表的C ++优先级队列类(C++ Priority Queue Class with Linked List)

带链接列表的C ++优先级队列类(C++ Priority Queue Class with Linked List)

我的c ++代码存在两个问题(测试文件如下):

我似乎无法弄清楚为什么它没有突破while循环,在运行时,它卡在循环“7对325”。

所以它应该进入temp的下一个节点,它将为null,然后跳转到它将它添加到队列末尾的部分。 但它只是循环和循环。

我的第二个问题是我已经注释掉的函数,queue1.back,无论什么时候运行,它只是出错并给出看起来像是地址,但.front()函数工作得很好。

我正在使用的测试文件是这样的:

89 Alex

325 Rob

72 Joy

91 Bob

using namespace std;

class Person
{
    friend class Pqueue;
    public:
        int priority;
        string name;
    };


    class PQueue
    {
        friend class Person;

        private:

        //Structure for my linked list.
        typedef struct node {
            Person data;
            struct node *next;
        }Node, *NodePtr;

        Node *head, *tail;

        public:
        //Prototype Functions
        PQueue(void);              //Initializer function
        bool empty(void);          //Test if empty
        int size(void);            //Return size
        void enqueue(Person *);    //Insert Node
        void dequeue(void);        //Remove Node
        Person* front(void);       //Access Next Node
        Person* back(void);        //Access last node

    };



    PQueue::PQueue()
   {
       head = NULL;
       tail = NULL;
   }



    bool PQueue::empty(){
        return (head == NULL);
    }



    void PQueue::enqueue(Person *myPerson){
        NodePtr np = (NodePtr) malloc(sizeof(Node));
        np->data = *myPerson;
        np->next = NULL;

        if(empty())
        {
             cout << "Making into creating the first node, of the linked list" <<endl;
             head = np;
             tail = np;
         }
         else { //Queue has more the one node
               Node* temp = head;
               if(np->data.priority > temp->data.priority) //If the priority is greater then the rest.
               {
                   head = temp;                            //Saving my head pointer
                   head->data = np->data;                  //Assigning new Data to the head pointer
                   head->next = temp;                      //Assigning the rest of the linked list back into head.
                   cout << "Making into creating the first node again, having to reassign." <<endl;
               }
               else{
                    //Searching where to place the node.
                    while(temp->data.priority > np->data.priority) //Searching if the next priority is higher then the passed.
                    {
                        cout << "Inside the while loop: " << np->data.priority << " versus "<<temp->data.priority <<endl;
                        if(temp->next == NULL)
                            break;
                        temp = temp->next;
                     }

            if(temp->next == NULL && np->data.priority < temp->data.priority) //Inserting at the end.
            {
                cout << "Making into creating the last node" <<endl;
                tail->next = np;
                cout << "Passing the function of creating the last node" <<endl;
            }
            else   //Inserting into the middle of the function.
            {
                cout << "Inserting in the middle of the queue" <<endl;
                np->next = temp->next;
                temp->next = np;
            }
        }
    }
}



void PQueue::dequeue(){
    if(empty()){
        cout << "\nAttempt to remove from an empty list." << endl;
        exit(1);
    }

    Person hold = head->data;
    NodePtr temp = head;
    head=head->next;
    if (head == NULL) tail = NULL;
    free(temp);
}

Person* PQueue::front(){
    //Person &temp = head->next->data;
    //Person &temp = head->data;
    Person &temp = head->data;
    return &temp;
}

Person* PQueue::back(){
    if(empty()){
        cout << "\nNo entries in list." << endl;
        exit(1);
    }
    Person &temp = tail->data;
    return &temp;
}

int main() {
    cout << "Starting main" << endl;
    PQueue queue1; //Creating my queue.
    cout << "Created Queue" << endl;
    Person tempPerson;
    ifstream inFile;
    inFile.open("/tmp/temp");
    cout << "going into while loop" << endl;

    while (inFile >> tempPerson.priority >> tempPerson.name){
        cout << "The priority is " <<  tempPerson.priority << " the name is " << tempPerson.name <<endl;
        queue1.enqueue(&tempPerson);
    }


    //Testing Section, trying to get .front and .back to work.
    Person *testPerson;
    testPerson = queue1.front();
    cout << "The TEST priority is " <<  testPerson->priority << " the TEST name is " << testPerson->name <<endl;
    /**
    Person *tailPerson;
    testPerson = queue1.back();
    cout << "The TEST priority is " <<  tailPerson->priority << " the TEST  name is " << tailPerson->name <<endl;
    **/

    queue1.dequeue();
    queue1.dequeue();
    queue1.dequeue();


    return 0;
}

I am having two issues with my c++ code (The test file is below):

I can't seem to figure out why its not breaking out of the while loop, when running, its stuck on the loop "7 versus 325".

So it should go into the next node of temp, which would be null, and then jump into the section where it adds it to the end of the queue. But its just looping and looping.

My second issue is with the the function I have commented out, queue1.back, whenever that is ran, it just errors out and gives what appears to be the address, but the .front() function works just fine.

The Test File I am working with is like this:

89 Alex

325 Rob

72 Joy

91 Bob

using namespace std;

class Person
{
    friend class Pqueue;
    public:
        int priority;
        string name;
    };


    class PQueue
    {
        friend class Person;

        private:

        //Structure for my linked list.
        typedef struct node {
            Person data;
            struct node *next;
        }Node, *NodePtr;

        Node *head, *tail;

        public:
        //Prototype Functions
        PQueue(void);              //Initializer function
        bool empty(void);          //Test if empty
        int size(void);            //Return size
        void enqueue(Person *);    //Insert Node
        void dequeue(void);        //Remove Node
        Person* front(void);       //Access Next Node
        Person* back(void);        //Access last node

    };



    PQueue::PQueue()
   {
       head = NULL;
       tail = NULL;
   }



    bool PQueue::empty(){
        return (head == NULL);
    }



    void PQueue::enqueue(Person *myPerson){
        NodePtr np = (NodePtr) malloc(sizeof(Node));
        np->data = *myPerson;
        np->next = NULL;

        if(empty())
        {
             cout << "Making into creating the first node, of the linked list" <<endl;
             head = np;
             tail = np;
         }
         else { //Queue has more the one node
               Node* temp = head;
               if(np->data.priority > temp->data.priority) //If the priority is greater then the rest.
               {
                   head = temp;                            //Saving my head pointer
                   head->data = np->data;                  //Assigning new Data to the head pointer
                   head->next = temp;                      //Assigning the rest of the linked list back into head.
                   cout << "Making into creating the first node again, having to reassign." <<endl;
               }
               else{
                    //Searching where to place the node.
                    while(temp->data.priority > np->data.priority) //Searching if the next priority is higher then the passed.
                    {
                        cout << "Inside the while loop: " << np->data.priority << " versus "<<temp->data.priority <<endl;
                        if(temp->next == NULL)
                            break;
                        temp = temp->next;
                     }

            if(temp->next == NULL && np->data.priority < temp->data.priority) //Inserting at the end.
            {
                cout << "Making into creating the last node" <<endl;
                tail->next = np;
                cout << "Passing the function of creating the last node" <<endl;
            }
            else   //Inserting into the middle of the function.
            {
                cout << "Inserting in the middle of the queue" <<endl;
                np->next = temp->next;
                temp->next = np;
            }
        }
    }
}



void PQueue::dequeue(){
    if(empty()){
        cout << "\nAttempt to remove from an empty list." << endl;
        exit(1);
    }

    Person hold = head->data;
    NodePtr temp = head;
    head=head->next;
    if (head == NULL) tail = NULL;
    free(temp);
}

Person* PQueue::front(){
    //Person &temp = head->next->data;
    //Person &temp = head->data;
    Person &temp = head->data;
    return &temp;
}

Person* PQueue::back(){
    if(empty()){
        cout << "\nNo entries in list." << endl;
        exit(1);
    }
    Person &temp = tail->data;
    return &temp;
}

int main() {
    cout << "Starting main" << endl;
    PQueue queue1; //Creating my queue.
    cout << "Created Queue" << endl;
    Person tempPerson;
    ifstream inFile;
    inFile.open("/tmp/temp");
    cout << "going into while loop" << endl;

    while (inFile >> tempPerson.priority >> tempPerson.name){
        cout << "The priority is " <<  tempPerson.priority << " the name is " << tempPerson.name <<endl;
        queue1.enqueue(&tempPerson);
    }


    //Testing Section, trying to get .front and .back to work.
    Person *testPerson;
    testPerson = queue1.front();
    cout << "The TEST priority is " <<  testPerson->priority << " the TEST name is " << testPerson->name <<endl;
    /**
    Person *tailPerson;
    testPerson = queue1.back();
    cout << "The TEST priority is " <<  tailPerson->priority << " the TEST  name is " << tailPerson->name <<endl;
    **/

    queue1.dequeue();
    queue1.dequeue();
    queue1.dequeue();


    return 0;
}

原文:https://stackoverflow.com/questions/36096133
更新时间:2023-02-16 09:02

最满意答案

这是一个异步问题。 Fetch正在执行异步Ajax调用,它将返回但尚未设置任何值。 做那样的事情:

this.currentUser.bind("change:id", function(){
  //your console logs
});

当获取成功并且在模型上设置了id时,将调用日志。


This is an asynchronous problem. Fetch is doing an asynchronous Ajax call, it will return but no values will be set yet. Do something like that:

this.currentUser.bind("change:id", function(){
  //your console logs
});

When the fetch succeed and an id is set on the model, the logs will be called.

相关问答

更多
  • 你没有在colMeans函数colMeans xbar归零。 如果我这样做: arma::vec colMeans(arma::mat data){ int n_0 = data.n_rows; arma::vec xbar; xbar.zeros(data.n_cols); for(int i = 0; i < data.n_rows; i++){ for(int j = 0; j < data.n_cols; j++){ xbar[j] += d ...
  • 这是有效的,但它停在BA ...所以你可以说$to = 'BC'; 或者你可以投入$to++; 在你宣布$to之后。 $from= 'A'; $to = 'BB'; while ($from !== $to) { echo $from++; } $from= 'A'; $to = 'BB'; $to++; while ($from !== $to) { echo $from++; } 如果您使用的是PHP 5.5,则可以使用生成器。 function alphaRange($from, ...
  • 您需要这样做来过滤掉空的服务包。 Query query = session.createQuery("from RatePlan plan fetch all properties where plan.servicePackages is not empty"); You need to do this to filter oout the servicepackages which are empty. Query query = session.createQuery("from RatePla ...
  • 我已经在过去写过你,版本4.6.0不支持使用冻结列编辑网格。 为了使代码工作,必须在每次更改网格内容后执行许多操作。 必须调整冻结div的位置并明确设置冻结div中每行的高度和宽度。 您可以在此处和此处找到代码中必须使用的示例。 现在存在更简单的解决方案。 如果您只是将版本jqGrid 4.6替换为github中当前的一个免费jqGrid代码
    首先,在setup : pinMode(buttonPin , INPUT); 其次, setting==3时你的期望是什么? 您没有重新加载/更新brightR brightG brightB的变量。 因此,当您更改setting ,您将失去亮度的变化 First, in setup: pinMode(buttonPin , INPUT); Second, what are you expected when setting==3? You aren't reloading/updating the ...
  • 该功能按预期工作。 over (order by time_)是over (order by time_ range unbounded preceding)的快捷方式over (order by time_ range unbounded preceding) ,它是over (order by time_ range between unbounded preceding and current row)的快捷方式over (order by time_ range between unbounded ...
  • 从Except() (强调我的) 的文档 : 通过使用默认的相等比较器来比较值,生成两个序列的集合差异 。 因此, Except()返回一个集合 ,这意味着它最多返回一次字符串。 既然你告诉它应该忽略这个案例,你就得到了你得到的输出。 要解决这个问题,请使用不对集合进行操作的方法,例如Where() : answerList = aList.Where( a => !blist.Contains(a, StringComparer.InvariantCultureIgnoreCase)) . ...
  • 这是一个异步问题。 Fetch正在执行异步Ajax调用,它将返回但尚未设置任何值。 做那样的事情: this.currentUser.bind("change:id", function(){ //your console logs }); 当获取成功并且在模型上设置了id时,将调用日志。 This is an asynchronous problem. Fetch is doing an asynchronous Ajax call, it will return but no values wil ...
  • 我没有看到提前输入的错误 在非工作情况1中 :你实际上是在说取消提前输入(这是esc所做的),然后你的代码显示显示绑定到input元素的任何内容,在这种情况下只是输入的内容 - “kg” 。 这是预期的行为(对于给定的代码)。 换句话说,如果未安装预先输入,则会得到完全相同的结果。 在非工作情况2中 ,它取决于您在删除后如何移动 - 如果您使用选项卡两次,提前输入默认建议选择'kg',因此第一个选项卡选择它然后第二个移动焦点,所以我我希望它被设置为'kg'对象。 如果你在删除/退格后点击其他地方,那么值是空 ...
  • 尝试var posY = event.pageY - popupHeight - 1; 确保从光标位置略微创建弹出窗口。 我认为问题是Firefox允许十进制值甚至像素位置。 这意味着弹出窗口正好在光标下面创建,这当然意味着你已经离开了.col_hover和mouseout fires,这意味着你回来了。冲洗并重复。 Try var posY = event.pageY - popupHeight - 1; to ensure the popup is created a bit off from the ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)