如何使用此链接列表实现? [英] How do I use this Linked List implementation?
问题描述
我正在从Goodrich学习C ++的数据结构和算法。他们已经给出了这个LinkedList实现。我了解代码,但不是,但是我不能在主类中使用它。如何构造实例并进行插入,删除?例如,我试图按如下方式创建该类的实例:
I am learning data structures and algorithms for C++ from Goodrich. They have given this LinkedList implementation. I understand the code but I am not but I am not able to use this in main class. How do I construct an instance and make insert, delete? For example I tried to create an instance of the class as follows:
StringLinkedList()L;
但显示错误:预期为;在‘L
But it is showing the error: expected ";" before 'L
#include <iostream>
#include <string>
using namespace std;
class StringNode {
private:
string elem;
StringNode* next;
friend class StringLinkedList;
};
class StringLinkedList{
public:
StringLinkedList();
~StringLinkedList();
bool empty() const;
const string& front() const;
void addFront(const string& e);
void removeFront();
private:
StringNode* head;
};
StringLinkedList::StringLinkedList()
:head(NULL) {}
StringLinkedList::~StringLinkedList()
{while (!empty()) removeFront();}
bool StringLinkedList::empty() const
{return head==NULL;}
const string& StringLinkedList::front() const
{return head->elem;}
void StringLinkedList::addFront(const string& e){
StringNode* v = new StringNode;
v->elem=e;
v->next = head;
head=v;
}
void StringLinkedList::removeFront(){
StringNode* old=head;
head = old->next;
delete old;
}
int main () {
}
推荐答案
括号()
表示函数调用。如果要声明变量,语法为
Brackets ()
indicate a function call. If you want to declare a variable the syntax is
Typename variable_name;
可选地,您可能需要将参数传递给构造函数
Optionally, you may need to pass parameters to a constructor
Typename variable_name(param);
在C ++ 11中,统一的初始化语法使您可以使用 {}
但我离题了。无论哪种方式,它们都在变量名之后 之后出现。
在您的情况下,这可行:
In C++11 the uniform initialisation syntax allows you to use {}
but I digress. Either way they come after the variable name.
In your case, this works:
StringLinkedList L;
When you say
StringLinkedList() L;
编译器看到一个类型名,然后期望一个变量名,但是得到( )
在名称 L
之前(顺便说一句,它可能应该使用更长的名称),因此决定您必须进行函数调用,该函数调用应以a结尾分号。但这不是,它以 L;
结尾,所以您得到
the compiler sees a typename, then expects a variable name, but gets ()
before the name L
(BTW - it might deserve a longer name) so decided you must be making a function call, which should end with a semicolon. But it doesn't, it ends with L;
so you get
expected ";" before 'L
这篇关于如何使用此链接列表实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!