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;
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);
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;
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
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments