按功能检查列表是否为空

时间:2017-10-29 20:36:08

标签: c++

我有两个结构PQCell是我的链表中的一个单元格。 PriorityQueue包含指向由PQCell组成的链表的指针。如果我的列表为空,isEmpty应该返回true。但似乎无法做到正确。

struct PQCell
{
    int priority;
    PQCell *next;
};

struct PriorityQueue
{
    PQCell *head = new PQCell;

    PriorityQueue()
    {
      head->next = NULL;
    }
};

bool isEmpty(const PriorityQueue& q)
{
  if(head == NULL)
  {
    return true;
  }

  else
  {
   return false;
  }
}

int main()
{
  PriorityQueue q;
  isEmpty(q);

  return 0;
}

3 个答案:

答案 0 :(得分:0)

这是我的解决方案

#include <bits/stdc++.h>

using namespace std;
struct PQCell
{
    int priority;
    PQCell *next;
};

struct PriorityQueue
{
    PQCell *head;

    PriorityQueue()
    {
      head = NULL;
    }
};

bool isEmpty(const PriorityQueue& q)
{
  if(q.head == NULL) // I changed the condition so that i checked if the head is NULL
  {
    return true;
  }

  else
  {
   return false;
  }
}

int main() 
{
  PriorityQueue q; 

  if(isEmpty(q))
    cout<<"it is empty";
  else
    cout<<"it is not empty";
  return 0;
}
希望这会有所帮助。

答案 1 :(得分:0)

有不同的方法来定义队列的逻辑,但是当头指针为空时,我发现更容易使isEmpty返回true,而不是像你看到的那样查看head-&gt;(哪个工作,需要你在构造函数中创建头节点,浪费内存而不需要)。另外,我会将isEmpty作为PriorityQueue上的一个方法,而不是一个独立的函数。

答案 2 :(得分:0)

如果头部包含队列中的下一个单元格并且该单元格的下一个单元格包含队列中的另一个单元格,那么当head为nullptr时,队列为空时,可能是:

struct PQCell
{
    int priority;
    PQCell *next;
    PQCell(): next(nullptr) {}

};

struct PriorityQueue
{
    PQCell *head;

    void add(PQCell *newcell)
    {
        if (isEmpty())
        {
            head = newcell;
            return;
        }

        PQCell *thiscell = head;
        PQCell *nextcell = thiscell->next;

        if (thiscell->priority < newcell->priority)
        {
            newcell->next = thiscell;
            head = newcell;
            return;
        }

        while (nextcell != nullptr)
        {
            if (newcell->priority > nextcell->priority)
            {
                thiscell->next = newcell;
                newcell->next = nextcell;
                return;
            }

            thiscell = nextcell;
            nextcell = thiscell->next;
        }

        nextcell = newcell;
    }

    PriorityQueue(): head(nullptr){}
    bool isEmpty() {return head == nullptr;}
};



int main()
{
    PriorityQueue q;
    std::cout << "queue is " << (q.isEmpty() ? "" : "not ") << "empty" << std::endl;

    PQCell c1;
    c1.priority = 5;
    q.add(&c1);

    PQCell c2;
    c2.priority = 15;
    q.add(&c2);

    PQCell c3;
    c3.priority = 3;
    q.add(&c3);

    std::cout << "queue is " << (q.isEmpty() ? "" : "not ") << "empty" << std::endl;
    std::cout << "head of the queue priority: " << q.head->priority << std::endl;

    return 0;
}

打印:

queue is empty
queue is not empty
head of the queue priority: 15
相关问题