c++ 将第一个值添加到双向链表中,同时遍历链表并输出结果[已关闭]

c2e8gylq  于 2022-11-27  发布在  其他
关注(0)|答案(2)|浏览(158)

**已关闭。**此问题为not reproducible or was caused by typos。目前不接受答案。

这个问题是由一个打字错误或一个无法再重现的问题引起的。虽然类似的问题在这里可能是on-topic,但这个问题的解决方式不太可能帮助未来的读者。
昨天关门了。
Improve this question
我试图先将每个数据添加到双向链表中,然后显示数据,但它没有给我正确的输出。

#include <iostream>
using namespace std;

class node {
public:
    string name;
    string title;
    node* next;
    node* prev;
};
class doublylinkedlist {
public:
    node* head = NULL;
    void addfirst(string name, string title) {
        node* p = new node();
        p->name = name;
        p->title = title;
        p->prev = NULL;
        p->next = head;
        if (head != NULL)
            head->prev = p;

        head = p;
    }
    void print() {
        node* w = head;
        if (head = NULL)
            cout << "the linked list is an empty one" << endl;
        else {
            while (w != NULL)
            cout << "our artist name is that " << w->name << endl;
            cout << "our song title is that" << w->title << endl;
            w = w->next;
        }
    }
};

int main()
{
    std::cout << "Hello World!\n";
    doublylinkedlist dll;
    dll.addfirst("Henok", "flower");
    dll.addfirst("terrence", "now");
    dll.addfirst("walter", "dog");
    dll.print();

}

我希望先添加数据,然后从“Walter dog、Terrence now和Henok flower”中取出,但取出的结果不正确。我的代码有什么问题?

zfciruhq

zfciruhq1#

问题不在“addfirst”函数,而在“print”函数。
你把“=”和“==”弄混了,而且你忘了在while循环的语句周围加括号。
请使用下面的“打印功能”更正:

void print() {
        node* w = head;
        if (head == NULL)
            cout << "the linked list is an empty one" << endl;
        else {
            while (w != NULL) {
                cout << "our artist name is that " << w->name << endl;
                cout << "our song title is that" << w->title << endl;
                w = w->next;
            }
        }
    }
jyztefdp

jyztefdp2#

为什么要创建自己的容器?如果这是为C++类创建的,那么您应该学习如何使用标准库中的容器。我已经包含了使用std::list提供解决方案的代码。我还用“\n”替换了std::endl; std::endl会产生\n但也会清除数据流,在此情况下并不需要。

#include <iostream>
#include <list>

struct node {
  std::string name_;
  std::string title_;
};

int main(int argc, char* argv[]) {
  std::list<node> dllist;
  dllist.push_front(node{"Henok", "flower"});
  dllist.push_front(node{"terrence", "now"});
  dllist.push_front(node{"walter", "dog"});
  if (dllist.empty()) {
    std::cout << "The list is empty\n";
  } else {
    for (auto& n : dllist) {
      std::cout << "our artist name is that " << n.name_ << '\n';
      std::cout << "our song title is that " << n.title_ << '\n';
    }
  }
}

相关问题