简体   繁体   中英

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;
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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM