在C++中实现双向链表时面临的调试问题 [英] Facing debugging problem when implementing doubly linked list in C++

查看:90
本文介绍了在C++中实现双向链表时面临的调试问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现一个双向链表,其中每个节点都有两个指针。一个指向列表中的下一个节点,而另一个指向上一个节点。 节点结构由一个整数和指向列表中下一个节点的节点指针组成。另一个指针指向列表中的前一个指针。 该类包含两个节点指针:一个指向列表的头部,另一个指向列表的尾部。如果列表为空,则它们都应指向nullptr。

我的代码是

#include <iostream>
using namespace std;

struct Node
{
    int value;
    Node *next;
    Node *tail; //previous node pointer
};

class LinkedList
{
private:
    Node *head;
    Node *tail;

public:
    int size;
    LinkedList()
    {
        head = nullptr;
        tail = nullptr;
        size = 0;
    }

    int length()
    {
        return size;
    }

    void append(int val)
    {
        if (head == nullptr)
        {
            head = new Node(val);
            return;
        }

        // Iterate to end of list
        Node *current;
        current = head;
        while (current->next != nullptr)
        {
            current = current->next;
        }

        // Link new node to end of list
        current->next = new Node(val);
    }
};

int main()
{

};

我收到此错误:

error: no matching constructor for initialization of 'Node'
            head = new Node(val);
                       ^    ~~~
linked_list.cpp:4:8: note: candidate constructor (the implicit copy constructor) not viable: no known conversion from 'int' to 'const Node' for 1st
      argument
struct Node
       ^
linked_list.cpp:4:8: note: candidate constructor (the implicit default constructor) not viable: requires 0 arguments, but 1 was provided
2 errors generated.

欢迎任何有关我在哪里可以阅读有关此主题的更多信息的建议/链接:)预先感谢您!

推荐答案

在Other to Callnew Node(val)中,其中valint,您的Node需要将int作为参数的构造函数。

也许:

struct Node
{
    int value;
    Node *next;
    Node *tail; 

    Node(int v) : value(v), next(nullptr), tail(nullptr) { }
};

这篇关于在C++中实现双向链表时面临的调试问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆