I am implementing a doubly linked list where each node has two pointers. One points to the next node in the list, while the other points to the previous node. The node struct consists of an integer and a node-pointer to the next node in the list. And another pointer to the previous pointer in the list. The class contains two node pointers: one to the head of the list, and one to the tail of the list. If the list is empty, they should both point to nullptr.
My code is
#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()
{
};
I am getting this error:
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.
Any advice/links about where I can read more about this topic is welcome:) Thank you in advance!
CodePudding user response:
In other to call new Node(val)
where val
is an int
, your Node
needs a constructor that takes an int
as an argument.
Perhaps:
struct Node
{
int value;
Node *next;
Node *tail;
Node(int v) : value(v), next(nullptr), tail(nullptr) { }
};