gpt4 book ai didi

C++链表isEmpty函数

转载 作者:行者123 更新时间:2023-11-30 03:24:09 25 4
gpt4 key购买 nike

我想检查 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;
}

但是我不能通过同一类的对象在其他类中使用这个函数。

如何使用可在另一个类中通过同一类的对象访问的函数 检查空列表?

最佳答案

您收到的错误是由于您将函数声明为 bool isEmpty(LinkedListNode) 但您试图将其定义为 bool isEmpty(LinkedListNode*)。不同之处在于,在定义中有一个指针,而在声明中只有一个对象。您必须选择一个,因为它们是完全不同的东西。

就是说,我完全不明白为什么您需要参数来检查您的列表是否为空。只需完全放弃参数并使用 if ( head->next == NULL ) - 非静态成员函数总是通过类的实例调用。

只是为了完整性,列表中的第一项由 head 指向,因此为了检查列表中是否有任何内容,您应该检查它是否为空指针:

bool IntLinkedList::isEmpty() const
{ //added const for const-correctness, should be added to declaration as well
return head == nullptr;
}

关于C++链表isEmpty函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49934750/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com