C++ 如何在全局函数中访问链表的开头和结尾?
在我的考试中,我有一个问题,我必须在我的类之外实现一个全局函数,以反转作为参数传入的列表的内容。我不知道该怎么办。 如果我必须实现IntList类中的反向函数,我知道该如何实现:C++ 如何在全局函数中访问链表的开头和结尾?,c++,singly-linked-list,C++,Singly Linked List,在我的考试中,我有一个问题,我必须在我的类之外实现一个全局函数,以反转作为参数传入的列表的内容。我不知道该怎么办。 如果我必须实现IntList类中的反向函数,我知道该如何实现: const int IntList::front() const { return head->data; } int IntList::count() const { int count = 0; for (IntNode *i = head; i != 0; i = i->ne
const int IntList::front() const
{
return head->data;
}
int IntList::count() const
{
int count = 0;
for (IntNode *i = head; i != 0; i = i->next)
{
++count;
}
return count;
}
void IntList::reverse(IntList &list)
{
int counter = count();
while (counter != 0)
{
list.push_front(front());
pop_front();
--counter;
}
}
但是,在测试中,我无法访问count()函数来计算需要调用列表中的push_front()和pop_front()的次数。我想知道是否有一种方法可以访问私有数据成员以循环浏览列表?还是我的想法完全错了
我得到的是:
struct IntNode
{
int data;
IntNode *next;
IntNode(int data) : data(data), next(0) {}
};
class IntList
{
private:
IntNode *head;
IntNode *tail;
public:
IntList();
IntList(const IntList &cpy);
IntList & operator=(const IntList &rhs);
~IntList();
bool empty() const;
int front() const; //implement
void push_front(int value); //implement
void pop_front(); //implement
void push_back(int value); //implement
void pop_back(); //implement
};
void reverse(IntList &list); //implement as global function
下面的实现解决了您的问题
void reverse(IntList &list)
{
IntList previousList = list; //Store the previous list.
list = IntList(); //Initialise a new List.
while(!previousList.empty())
{
int frontValue = previousList.front();
list.push_front(frontValue);
previousList.pop_front();
}
}
您不需要知道列表要反转多长时间。那么,
count()
如何知道它应该停止计数?在一个无关的注释中,从函数返回常量值没有任何意义。调用者无论如何都可以将其分配给非常量变量。但是返回对常量值的引用是完全不同的。您确定要给出此列表结构吗?如果没有API来填充它?可能他必须构建API作为任务的一部分。不管怎样,回答这部分问题:不;没有办法访问私有成员(也就是说,除非一个公共方法有意提供),而且不应该这样做。将它们设置为私有的原因是将接口(对象的功能)与实现(对象的功能)分开。对象外部的代码应该只关注自身并了解接口,将成员标记为私有是一种强制执行此操作的工具。Oops!抱歉,我做了一次编辑来修复这篇文章。我包含了其他函数,并删除了我意外添加到front()函数中的常量