I am new in c++ and I am learning linked list. However, I encountered some trouble.
For the normal case, when we define a linked list, here is the Node structure:
struct Node{
int data;
Node* next;
};
However, how can we define a linked list when the structure become like this:
struct Node{
int data;
Node** next; // Double pointer instead
};
I am quite confused with the double pointer, what should we assign to "next"?
For example, when we are inserting node at the beginning, when we assign the value of head into newPtr->next:
newPtr->next = &head? Is that right?
Thanks all of you.
I'm not sure with this but I just want to share my thoughts since I'm also beginning to learn about pointers. Please correct me if I'm wrong.
#include <iostream>
int main()
{
int **p = new int*; // Pointer to a pointer.
int *q = new int; // Pointer.
// Assigning the value of 5 to where q points to.
// The "*" is used as a dereference operator
// meaning that it assigns 5 to where q is pointing to.
*q=5;
// Here you are pointing p to point to q.
// That is why it is called a pointer to a pointer.
// The "*" here is used as pointer to point to another pointer.
*p=q;
// Then here you can access the value of the p by dereferencing
// it twice.
std::cout << **p << std::endl;
// Outputs 5.
return 0;
}
As what the others said in the comments you are creating a pointer to a pointer. int *p means it can point to a data directly while int **q means it can point to another pointer, in this case *p. The number of * tells how deep you are going. Assuming that you want your Node to have a two pointers, then you have to do something like this:
struct Node
{
int data;
Node *next, *prev;
}
It is also called Doubly Linked List. Where you can traverse forward and backward.
Related
Isn't this a way to store a node in an array? When I try to run it I get a segmentation fault. I know that happens if you try to access memory that you do not have permission for.
In this code am I not assigning a node in an array and printing its data?
struct Node{
int data;
struct Node* next;
};
struct Node* head = NULL;
int main(){
struct Node* arr[10];
head->data = 2;
head->next = NULL;
arr[1] = head;
std::cout << arr[1]->data;
}
You are not dealing with Nodes's here, but Node pointers. They are not pointing to valid memory, unless you allocate it.
Also, don't use NULL, use nullptr instead.
head = nullptr;
head->data = 42; // this is UB, could be a segfault
If you want to do that, you have to allocate it
head = new Node{};
head->data = 42; //ok
The same logic applies for arr
arr[1] = new Node{}; // now arr[1] is pointing to valid memory
I'm not sure why you want an array of Node pointers, though. Your Node struct looks like a conventional linked-list Node, and there's a linked-list tag, so I'm guessing you want to implement linked-lists.
In that case, you don't need an array of Node pointers at all. The entire linked-list should be connected through the head.
If you just want an array of Nodes, then you can do that, and not worry about memory allocation at all.
Node arr[10] {};
arr[1].data = 42; // ok
I am trying to create a graph using linked list styled nodes where each node is a structure containing a key and an address to the next node, but I want to join multiple nodes to one node so I tried creating an array of pointers to structure and initialize them using new dynamically but it throws an error saying that it "cannot convert node*** to node** in assignment".
I have tried using struct node* next[] but it didn't work well. What am I missing here? Should I just use a vector of pointers instead of an array?
struct node
{
int key;
struct node** next;
};
int main()
{
struct node A;
A.key = 12;
A.next = new node**[2];
return 0;
}
Should I just use a vector of pointers instead of an array?
This is often an ideal solution. This would fix the memory leak that your program has (or would have if it compiled in the first place). An example:
struct node
{
int key;
std::vector<node*> next;
};
// usage
A.next.resize(2);
Vector does have space overhead, which can be a problem with big graphs because the total overhead increases linearly in relation to number of nodes. If vector is not appropriate for you, an alternative is std::unique_ptr, which does not have any overhead compared to a bare pointer:
struct node
{
int key;
std::unique_ptr<node[]> next;
};
// usage
A.next.reset(new node*[2]);
new node**[2];
What am I missing here?
You're attempting to create an array of node** when you need an array of node*.
Should I just use a vector of pointers instead of an array?
YES!
After including the vector library, then in your structure, you would have a member like this:
std::vector<node*> next;
This is the C++ approach, using raw pointers is the C approach.
As an encyclopedian information though, with raw pointers, you would do:
A.next = new node*[2];
which means an array of two pointers.
So I currently have a simple struct (linkedlist) that I will be using in a HashMap:
struct Node {
std::string key, value;
Node* head;
}
I'm currently trying to dynamically allocate an array with pointers to each struct. This is what I have right now ...
Node* nodes = new Node[100]
I understand this allocates an array of 100 nodes into memory (which I will have to delete later on); however, upon iteration to try to transverse these nodes (which I an implementing as a linked list)...
for (int x = 0; x < 100; x++) {
Node current = nodes[x]; // Problem is I wanted an array to node pointers. This is not a pointer.
while (current != nullptr) { // this isn't even legal since current is not a pointer.
// DO STUFF HERE
current = current.next; // This is not a pointer access to a method. I'm looking to access next with current->next;
}
}
Hopefully I was clear enough. Can someone how to allocate a dynamic array of pointers to structs? So far I'm able to dynamically allocate an array of structs, just not an array of pointers to structs.
There are two approaches. Either you allocate an array of structures and introduce one more pointer that will point to the element in the array that will play the role of the head.
For example
Node *head = nodes;
(in this case head points to nodes[0])
After the list will not be needed you have to delete it using operator
delete [] nodes;
Or you can indeed to allocate an array of pointers to the structure like this
Node **nodes = new Node *[100];
But in this case each element of the array in turn should be a pointer to a dynamically allocated object;
And to delete the list you at first have to delete each object pointed to by elements of the array for example in a loop
for ( int i = 0; i < 100; i++ ) delete nodes[i];
and then to delete the array itself
delete [] nodes;
It is a good idea to initialize each element of the array with zeroes when the array is allocated for example
Node **nodes = new Node *[100]();
I suggested you this structure:
class myList {
struct Node {
string value;
Node* next;
}
/*Public methods .. Add/Set/Get/Next/isEmpty.. etc ... */
Node* head, *tail;
};
in main:
myList* lis = new myList[number];
then you have number of lists! and do all work in class by method's and operators, like if you want the next node just call lis[0].getNext();
if you want to skip current node dolis[0].Next(); ... etc ..
this how to work, what you try to do is looks like C program!
I tried asking my question but I don't appear to be asking it correctly and I have been stuck for 2 months now. (which is sad)
For reference only: I built a linked list from nodes:
struct node {
int number;
node *next; };
To link these in main I used -> to assign values
void insertAsFirstElement(node *&head, node *&tail, int number){
node *temp = new node;
temp->number = number;
temp->next = NULL;
head = temp;
tail = temp; }
Now I am trying to make a skiplist, which should have the same structure as my original node except the node* next should be an array of pointers of type node.
struct node {
int number;
node *next[3];
};
I am getting confused on how to have an array of node pointers. I notice they tend to look like this: node **next and then declared to have memory allocated dynamically. I just want my arrays to be of size 4. So [3].
My problem is how can I create new nodes with the array of node pointers in main() and put something in the first slot of the nodes array?
This does not work for putting things in the array but it does work for putting in the number.
void insertAsFirstElement(node *&head, node *&tail, int number){
node *temp = new node;
temp->number = number;
cout<<temp->number<<endl;
temp->next[0] = tail;
cout<<temp->next[0]<<endl;
head->next[0] = temp;
cout<<head->next[0]<<endl;
}
Please help me.
The -> operator is a shorthand.
Without the -> operator, you would write
(*var).prop;
With the -> operator, you write:
var->prop;
Thus, to store a node in the first position of the list, you write:
void StoreNode(node *node){
node *temp = new node;
temp->next[0]=node;
}
And to retrieve data from a node in the list, you can write:
temp->next[0]->number
which is the same as writing
(*temp).next[0]->number
which is the same as writing
( *((*temp).next[0]) ).number
This line of your code seems a little confused:
void insertAsFirstElement(node *&head, node *&tail, int number){
Remember, you are just passing your function the address of a node. Therefore, all you need is
void insertAsFirstElement(node *head, node *tail, int number){
Inside the function itself, you will have to find the correct location in the list, that is when you get into the ** notations.
The code at a first look seems ok. An array of pointers is just that, an array of elements where each one is a pointer, and you use it exactly with the syntax your code shows.
Note however that when declaring an array of pointers inside a class the elements are not automatically initialized so you probably want to fix the elements that are not used yet to NULL. Moreover in a skip list you're probably going to need to know at which "level" the node has been inserted.
Are you sure your problem is in that part? Often with C++ a mistake doesn't appear right in the point it's done, but much later. This happens because of the "undefined behavior" rule of the language (aka "programmers never make mistakes").
I am tring to intialize an array of pointers to a NODE struct that I made
struct Node{
int data;
Node* next;
};
the private member of my other class is declared as
Node** buckets;
It is currently initialised as
buckets = new Node*[SIZE]
Is there anyway to initialize the array so that its members point to NULL or some other predefined Node pointer?
EDIT: Im looking for a means to initilize it without trying to generate a for loop to traverse through the full lenght of the array. The size of the array is determined at runtime.
EDIT 2: I tried std::fill_n(buckets, SIZE_OF_BUCKET, NULL); but the compiler gives the error "cannot convert from 'const int' to 'Node *'" I am using visual studio 2008. Is there something wrong that I am doing?
First of all, the simplest solution is to do the following:
Node** buckets = new Node*[SIZE]();
As litb previously stated, this will value initialize SIZE pointers to null pointers.
However, if you want to do something like Node **buckets and initialize all of the pointers to a particular value, then I recommend std::fill_n from <algorithm>
Node **buckets = new Node*[SIZE];
std::fill_n(buckets, SIZE, p);
this will set each Node*' to p after allocation.
In addition, if you want the Node to have sane member valuesupon construction, the proper way is to have a constructor. Something like this:
struct Node {
Node() : data(0), next(NULL){}
Node(int d, Node *n = NULL) : data(d), next(n) {}
int data;
Node* next;
};
That way you can do this:
Node *p = new Node();
and it will be properly initialized with 0 and NULL, or
Node *p = new Node(10, other_node);
Finally, doing this:
Node *buckets = new Node[N]();
will construct N Node objects and default construct them.
If you mean by array your array-of-pointers buckets, then yes. Just set buckets = NULL.
Edit: based on your question edit, just use memset.
memset(buckets, 0, NUM_ELEMENTS_IN_BUCKETS*sizeof(Node*));