我正在创建一个删除链表的头节点并使其成为另一个链表的头部的函数。我在名为LinkedList的外部类中创建了一个名为moveNode的函数原型,然后我在代码中定义了该函数。但是,我的编译器给了我错误消息说" class LinkedList :: Node是private"和#34; LinkedList :: Node * LinkedList:head是私有的。我不明白我需要做些什么来修复它。
#include <iostream>
#include <cstdlib>
using namespace std;
class LinkedList
{
public:
LinkedList() { head = NULL; } // default constructor
friend ostream& operator<<( ostream& os, const LinkedList &ll );
void insertHead( int item ); // insert at the head of the list
int count(int searchFor, const LinkedList &ll);
void moveNode(LinkedList &other, LinkedList ¤tList);
private:
class Node // inner class for a linked list node
{
public:
Node( int item, Node *n );
int data; // the data item in a node
Node *next; // a pointer to the next node in the list
};
Node *head; // the head of the list
};
LinkedList::Node::Node(int item, Node *n)
{
data = item;
next = n;
}
ostream& operator<<(ostream& os, const LinkedList &ll)
{
LinkedList::Node *current;
for(current = ll.head; current != NULL; current = current->next)
{
os << current->data << " ";
}
}
int LinkedList::count(int searchFor, const LinkedList &ll)
{
LinkedList::Node *current;
current = ll.head;
int howmanytimes = 0;
while(current != NULL){
if(current->data == searchFor)
{
howmanytimes++;
}
}
cout << searchFor << " appears in " << ll << " | " << howmanytimes << "time(s)" << endl;
}
void moveNode(LinkedList &other, LinkedList ¤tList)
{
LinkedList::Node *current = other.head;
if(current!=NULL)
{
current->next = currentList.head;
}
}
void LinkedList::insertHead(int item)
{
head = new Node(item, head);
}
答案 0 :(得分:1)
您没有在moveNode()
实施中对类名进行限定:
// note the LinkedList::
void LinkedList::moveNode(LinkedList &other, LinkedList ¤tList)
{
LinkedList::Node *current = other.head;
if(current!=NULL)
{
current->next = currentList.head;
}
}
话虽如此,此实现与您的描述不符:
一个删除链表的头节点并使其成为另一个链表的头部的函数
实际执行的内容看起来更像是这样的实现:
void LinkedList::moveNode(LinkedList &other, LinkedList ¤tList)
{
LinkedList::Node *current = other.head;
if (current != NULL)
{
other.head = current->next;
current->next = currentList.head;
currentList.head = current;
}
}
话虽这么说,这个方法应该重命名为moveHead()
。由于它不通过this
指针访问任何内容,因此甚至可以声明static
。否则,我建议重新实现它以至少删除currentList
参数,例如:
void LinkedList::moveHead(LinkedList &other)
{
LinkedList::Node *newhead = other.head;
if (newhead != NULL)
{
other.head = newhead->next;
newhead->next = this->head;
this->head = newhead;
}
}