开发者

printing a (singly) linked list in c++

OK, first I have my node structure

struct node {   
    string s;   
    node * next; 
};

And It's located within a class

    class strSet{
private:

    node * first;

And I can construct the list, and i've made checks to see it's being constructed (it is), but when i try and print it.. "Empty Set开发者_高级运维" is printed

This is my code to "print" it: (I've tried many variations of declaring a temp pointer, and still nothing)

node *temp = new node;
    temp = first;
    if (temp == NULL) cout << "Empty set" << endl;
    else {
    //  node * temp = new node;

        while (temp != NULL){
            cout << temp->s << endl;
            temp = temp->next;
        }
    }

Any help is appreciated, Thanks

EDIT: I have a function that makes a singleton list (this is for an assignment), the code is:

node *first = new node;
first->s = s;
cout << first->s << endl;
first->next = NULL;

The third line prints out the element when I add it

And yes i know there is a memory leak


node *temp = new node;

this line is unnecessary and leaks memory; The rest of the printing routine is correct, and therefore if "Empty Set" is printer therefore the set IS empty


From the small quantity of code you posted, it should work, so my guess would be that something is wrong with the construction of the list.

Now, there are some incoherences in your code - the useless "new node" for temp, as stated, but also having your (temp == NULL) ; this test could be directly operated with "first". Of course, make sure the strSet initializes first to null.

Then only you'd create temp before the while() and after the else. It's more logical (and a bit more optimal, though you're not winning much there - but you'll gain in readability).


node *temp = new node;
temp = first;

can be condensed to -

node *temp = first ; // An unnecessary memory leak in earlier case.

Other than that print logic seems to fine. You didn't show the important part of how the linked list is formed.


node *first = new node;
first->s = s;
cout << first->s << endl;
first->next = NULL;

This is not a linked list at all. You are just creating an instance of type node* and just copying the s to it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜