C++链表isEmpty函数
C++ Linked List isEmpty Function
我想检查C++ 中的链表是否为空。我关注 class:
class IntLinkedList
{
private:
struct LinkedListNode // Structure for linked list
{
int value;
struct LinkedListNode *next;
};
LinkedListNode *head; // List head pointer
public:
IntLinkedList(void) // Constructor
{ head = NULL; }
~IntLinkedList(void); // Destructor
void AppendNode(int);
void InsertNode(int);
void DeleteNode(int);
void DisplayList(void);
bool isEmpty(LinkedListNode*);
};
// isEmpty function
bool IntLinkedList::isEmpty(LinkedListNode *node)
{
bool status;
node = head;
if ( node->next == NULL )
status = true;
else
status = false;
return status;
}
但我不能通过相同 class 的对象在其他 class 中使用此功能。
如何使用 函数 检查空列表,而另一个 class 可以通过相同 class 的对象访问该空列表?
您遇到的错误是由于您将函数声明为 bool isEmpty(LinkedListNode)
但您试图将其定义为 bool isEmpty(LinkedListNode*)
。不同之处在于,在定义中有一个指针,而在声明中只有一个对象。你必须选择一个,因为它们是完全不同的东西。
就是说,我完全不明白为什么您需要参数来检查您的列表是否为空。只需完全放弃参数并使用 if ( head->next == NULL )
- 非静态成员函数总是通过 class 的实例调用。
为了完整性,列表中的第一项由 head
指向,因此为了检查列表中是否有任何内容,您应该检查它是否为空指针:
bool IntLinkedList::isEmpty() const
{ //added const for const-correctness, should be added to declaration as well
return head == nullptr;
}
正在关注 list.empty()
、
Returns whether the list container is empty (i.e. whether its size is
0).
两条建议:
有一个 size
变量来检查列表中的节点数,这样你的 isEmpty()
就是 return size == 0;
或者在您当前的实现中,只需修改为:
bool isEmpty() {
return head == null; // if head is null, there's no node in list
}
我想检查C++ 中的链表是否为空。我关注 class:
class IntLinkedList
{
private:
struct LinkedListNode // Structure for linked list
{
int value;
struct LinkedListNode *next;
};
LinkedListNode *head; // List head pointer
public:
IntLinkedList(void) // Constructor
{ head = NULL; }
~IntLinkedList(void); // Destructor
void AppendNode(int);
void InsertNode(int);
void DeleteNode(int);
void DisplayList(void);
bool isEmpty(LinkedListNode*);
};
// isEmpty function
bool IntLinkedList::isEmpty(LinkedListNode *node)
{
bool status;
node = head;
if ( node->next == NULL )
status = true;
else
status = false;
return status;
}
但我不能通过相同 class 的对象在其他 class 中使用此功能。
如何使用 函数 检查空列表,而另一个 class 可以通过相同 class 的对象访问该空列表?
您遇到的错误是由于您将函数声明为 bool isEmpty(LinkedListNode)
但您试图将其定义为 bool isEmpty(LinkedListNode*)
。不同之处在于,在定义中有一个指针,而在声明中只有一个对象。你必须选择一个,因为它们是完全不同的东西。
就是说,我完全不明白为什么您需要参数来检查您的列表是否为空。只需完全放弃参数并使用 if ( head->next == NULL )
- 非静态成员函数总是通过 class 的实例调用。
为了完整性,列表中的第一项由 head
指向,因此为了检查列表中是否有任何内容,您应该检查它是否为空指针:
bool IntLinkedList::isEmpty() const
{ //added const for const-correctness, should be added to declaration as well
return head == nullptr;
}
正在关注 list.empty()
、
Returns whether the list container is empty (i.e. whether its size is 0).
两条建议:
有一个 size
变量来检查列表中的节点数,这样你的 isEmpty()
就是 return size == 0;
或者在您当前的实现中,只需修改为:
bool isEmpty() {
return head == null; // if head is null, there's no node in list
}