简体   繁体   English

在C ++中打印(单个)链接列表

[英]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 而且我可以构造列表,并且已经检查过它正在构造中(是),但是当我尝试打印它时。“ Empty Set”被打印

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*的实例,然后将s复制到该实例。

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) ; 现在,您的代码中有些不连贯性-如前所述,对于temp而言,无用的“新节点”,但也有您的(temp == NULL); this test could be directly operated with "first". 该测试可以直接通过“ first”操作。 Of course, make sure the strSet initializes first to null. 当然,请确保首先将strSet初始化为null。

Then only you'd create temp before the while() and after the else. 然后只有您可以在while()之前和else之后创建temp。 It's more logical (and a bit more optimal, though you're not winning much there - but you'll gain in readability). 这更合乎逻辑(虽然您在那儿没有赢很多,但是您会获得更高的可读性)(并且更理想一些)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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