Re: linked list code won't compile
* Martin JHrgensen:
I got this piece of code, but I won't compile:
Although from a strictly a formal point of view it shouldn't, it
compiles fine with MSVC 7.1, MingW g++ 3.4.4, and Comeau Online 4.3.3.
Which compiler are you using?
#include <iostream>
Here you need to add
#include <ostream>
to be formally correct (very compilers require it, though).
using namespace std;
////////////////////////////////////////////////////////////////
struct link //one element of list
{
int data; //data item
link* next; //pointer to next link
};
As Phlip mentioned, remove those comments.
Then you'll see that the name "link" is not well chosen: it doesn't
document what it is.
Rename to "Node".
////////////////////////////////////////////////////////////////
class linklist //a list of links
{
private:
link* first; //pointer to first link
public:
linklist() //no-argument constructor
{ first = NULL; } //no first link
Use constructor initializer list.
void additem(int d); //add data item (one link)
void display(); //display all links
Applying mechanical cookbook-like guidelines, the "display" function
should be 'const'.
Applying common sense, it should not be a member of the class (never do
i/o in a non-i/o class, except for debugging).
When you move it outside, as a non-friend, you'll find that the class is
"incomplete" in the functionality it offers: more must be added in order
to be able to implement "display" as a non-friend non-member.
};
//--------------------------------------------------------------
void linklist::additem(int d) //add data item
{
link* newlink = new link; //make a new link
newlink->data = d; //give it data
newlink->next = first; //it points to next link
first = newlink; //now first points to this
}
//--------------------------------------------------------------
void linklist::display() //display all links
{
link* current = first; //set ptr to first link
while( current != NULL ) //quit on last link
{
cout << current->data << endl; //print data
current = current->next; //move to next link
}
}
////////////////////////////////////////////////////////////////
int main()
{
linklist li; //make linked list
li.additem(25); //add four items to list
li.additem(36);
li.additem(49);
li.additem(64);
li.display(); //display entire list
return 0;
Not necessary. The default is to return 0 from main. If concerned
about correct return value from "main", instead concentrate on catching
possible exceptions, and in case of exception, returning EXIT_FAILURE.
}
And again, those comments are more to write, more to read, can not be
checked by the compiler, do not contribute anything... Remove. :-)
Hth.,
- Alf
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?