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").
Related
guys I am desperately trying to learn how to manipulate linked lists and I am having a hard time. I can't understand most of the tutorials online and they all don't seem intuitive to me. I have successfully tried to append a node at the beginning of a linked list using a double pointer, but the nature of this double pointer isn't behaving like I thought it would. Please refer to my code below:
#include <iostream>
using namespace std;
class node{
public:
int value;
node* next;
};
void push2front(node** ptr, int n) //a node pointer is now equal to the address of the head node
{
cout<<"ptr: "<<ptr<<endl;
cout<<"*ptr: "<<*ptr<<endl;
node* new_node = new node(); //create a new head node
new_node->value = n;
new_node->next = *ptr;
*ptr = new_node;
return;
}
int main() {
node* head = new node();
node* second = new node();
node* third = new node();
int input = 54;
head->value = 1;
head -> next = second;
second->value = 2;
second->next = third;
third->value = 3;
third->next = NULL;
cout<<"head: "<<head<<endl;//address of the data member value of head
cout<<"&head->value: "<<&head->value<<endl;//address of the value data member of node head
cout<<"&head: "<<&head<<endl;//address of the head node itself
cout<<"head->next: "<<head->next<<endl;//address of the next node after head
cout<<second<<" "; //address of the data member of 2nd node
cout<<&second->value<<" ";//address of the data member of 2nd node
cout<<&second<<endl;//address of the 2nd node itself
push2front(&head, input); //pass the address of the actual head node as well as the user inputted integer
while (head!=NULL)
{
cout<<head->value<<" ";
head = head->next;
}
return 0;
}
the output of this program is as follows:
head: 0x921520
&head->value: 0x921520
&head: 0x7bfe08
head->next: 0x921540
0x921540 0x921540 0x7bfe00
ptr: 0x7bfe08
*ptr: 0x921520
54 1 2 3
I placed a lot of cout in the program to see what happens as the program runs. Everything is fine and DANDY until the moment the I call the push2front() function. Here are my questions:
1.) Am I correct when I think that &head->value or simply head is the address of the value data member of the head node? Because based on what my cout shows, this seems to be the case.
2.) So does that mean that &head is the ACTUAL address of the node?
3.) I always thought that the next part of any node points to the ACTUAL address of the node next to it? So essentially I thought that
head->next == &second? But it seems that (according to the cout) nodes apparently point to the address of the value data member in
another node?
4.) If head: 0x91520 == ptr: 0x91520 why does head->value work and *ptr->value doesn't?
head contains the address of the first node. That is, the address of the beginning of the memory occupied by that node. That is also the address of the value member of that node, because that node and its value member start at the same place.
head is a pointer, which is a variable. &head is the address of that pointer. Pointing to a thing is not the same as pointing to a variable that contains the thing's address.
Yes, if the list is constructed correctly, the next part of any node points to the next node, which is to say it contains the actual address of the next node. So head->next == second, which is the address of the second node, and also of the second node's value member. It is not the case that head-next == &second, because second is a pointer that is not part of the list at all.
(*ptr)->value works; *ptr->value doesn't. The pointer operator (->) takes precedence over the dereference operator (*), so when you try to use *ptr->value, the compiler sees that as *(ptr->value) and complains "what do you mean, ptr->value? ptr is a pointer to a pointer, not a pointer to a thing that has members."
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.
I'm new to C++ and I normally use Java, so I have a hard time to get into pointers and references. I have to do a variation of binary search tree with inner nodes and leaf nodes (only leafs contain the data).
class Node
Node *parent;
Node *left;
Node *right;
//other stuff
}
I need to implement operator<< which adds a new node with value to the tree.
//adding a node to tree
void operator<<(int value){
if(size == 0){
//stuff
} else {
Node* temp = root;
getLeaf(temp,value);
//other magic
//temp will be used to append a new node into tree,
//so it has to point to the actual node in the tree
delete temp;
}
}
The point of function getLeaf is to find a leaf (may or may not contain the desired value) and store it into temp, which needs to be accessible in the operator<< function.
int getLeaf( Node* temp, int value) const{
int depth = 0;
//goes trough all inner nodes until it finds specific leaf
while(temp->isInner()){
++depth;
if(value < temp->getValue()){ //searched value is smaller
temp = temp->getLeft(); // to left subtree
continue;
} else {
temp = temp->getRight(); //to rightsubtree
continue;
}
return depth;
}
I am really confused how to do this and what is the right combination of pointers and values. If I set
Node* temp = root;
getLeaf(temp,value);
won't root get overridden while traversing the tree in getLeaf function?
Plus I need temp to point to actual node in the tree, so I can append a new node into it.
Could you please explain?
Migrating from Java to C++ is a bit tough. Migrating from C++ to Java is equally tough. To make things easy you just need to experiment.
In C++, pointers are variables that point to the location of another variable in memory and references are pointers that syntactically behave like the variable whose address is pointed to.
When arguments are passed to a function, the function does NOT receive the original arguments but a copy of them. The work you did is implement the traversal based on the above concepts. So how does it all "magically" work?
Your function: getLeaf(Node *&temp, int value) searches the correct leaf node and assigns it to temp at which insertion is to be performed. temp here is a copy of a reference to the pointer temp(in operator <<). So when the reference temp is assigned to in getLeaf, the pointer temp in operator << it points to is modified.
If I set
Node *temp = root;
getLeaf(temp,value);
won't root get overriden while traversing the tree in getLeaf function?
Note here that temp and root are two different pointers that point to the same variable. The content of the pointers is the same, they aren't and hence root is NOT overridden, when temp is updated.
But there is a problem later on in the code. If you delete temp;, root will also be deleted at the end of insertion as delete deletes the content pointed to by the pointer. Do NOT delete a pointer that is not allocated by a new.
Provide a separate function to free the dynamically allocated memory used by the tree, and call it at the end when you are done experimenting.
It is difficult to understand how this node is being created, Can you please write step-wise what this set of code is actually doing, and what actions they represent?
void list::create_node(int value)
{
struct node *temp;// Please write in words the meaning of this statement
temp = new(struct node);// is this a dynamic node? )
temp->info = value;// is this value being assigned to this node?
if (last == NULL)// what is this set of code testing??
{
last = temp;// who is this last; the node which has been created?
temp->next = last; // is the node pointing to itself being only one node?
}
else
{
temp->next = last->next;((( // What is this statement saying?
last->next = temp;// What is this statement saying?
last = temp;// What is this statement saying?
}
}
void list::create_node(int value)
{
The above line declares a function that creates a node with the given value and inserts the node into the list. The code must be examined to see where the new node is inserted.
struct node *temp;
Declares a pointer to a node. The memory has not been allocated yet, only a pointer that will be used later.
temp = new(struct node);
Allocates memory for a node from the dynamic (runtime) memory area (a.k.a. heap). Calls the constructor of the node structure to initialize the memory, if a constructor exists.
The pointer temp is now pointing to the node object.
temp->info = value;
This assigns the value to the data field, info. Need the declaration of struct node in order to confirm this guess.
if (last == NULL)
{
Assuming that last is a pointer and points to the last node, this check is looking for an empty list. Common implementation is to have pointer values set to null to mark the end of the list.
last = temp;
temp->next = last;
}
The above code inserts the new node as the last node. The last pointer allows fast access to the end of the list. This allows for reverse iteration without having to traverse all the links to find the last node.
Some implementations set the next field to null to indicate the end of the list, others like this one, make it point to the last node.
else
{
temp->next = last->next;
At this point, the list is not empty.
The new node is made to point to the same node that the last node points to.
This is best understood by drawing the node boxes and arrows pointing to the nodes.
last->next = temp;
Updating the last node to point to itself. See the above section.
last = temp;
Updating the pointer to the last (end of list) node to point to the new node.
}
}
I suggest you draw the linked list and walk through this algorithm a couple of times to see how it works. Also review the singly linked list data type.
The circular reference of the last node may be confusing to you. This may not be the standard implementation that most books describe, but it is valid.
I am trying to teach myself linked-lists with node structs and was hoping someone could help me with this. I would take input from the command line and it would make me a nested list and I could output it.
Example:
Input: "1 2 3 4 5"
Output:"1 2 3 4 5"
There are two things I am having trouble with:
1) When I run the program I keep getting warning: ‘typedef’ was ignored in this declaration [enabled by default]
How can I get rid of this?
EDIT: I have changed this to typedef struct Node* NodePtr;
2) My code is not working properly. How can I fix this? I am trying to teach myself linked lists in C++.
typedef struct Node;
typedef Node* NodePtr;
struct Node{
int x;
NodePtr next;
};
int main ()
{
int n;
NodePtr head, ptr = NULL;
head = ptr;
while (cin >> n){
ptr = new Node;
ptr->x = n;
ptr->next = NULL;
ptr = ptr->next;
}
NodePtr bling = head;
while(bling != NULL){
cout << bling->x << endl;
bling = bling->next;
}
return 0;
}
Ideally what I want to do is to make a linked-list like the following.
1 -> 2 -> 3 -> NULL.
First, regarding the declaration of your structure and the pointer typedef you seem to want, there are a number of ways of doing this. The following will work in C or C++.
// declare NodePtr as a pointer to Node, currently an incomplete type
// C and C++ both allow you to declare a pointer to damn-near anything
// so long as there is an understanding of what it *will* be, in this
// case, a structure called Node.
typedef struct Node *NodePtr;
// Now declare the structure type itself
struct Node
{
int x;
NodePtr next;
};
That said, I honestly do not recommend doing this. Most engineers want a clear and syntax-visible definition that screams to them, "THIS IS A POINTER!" You may be different. I, personally would simply prefer this:
struct Node
{
int x;
struct Node *next; // omit the 'struct' for C++-only usage
};
So long as you, and equally important, other engineers reading your code, understand your usage of NodePtr as a pointer-to-node, then go with what works best in your situation. Pointer type declaration is near-religious to some, so just keep that in mind. Some prefer seeing those asterisks (I being one), some may not (sounds like you =P).
Note: there is one place that using a typedefed pointer-type can be beneficial in avoiding potential errors: multiple variable declarations. Consider this:
Node* a, b; // declares one Node* (a), and one Node (b)
Having a typedef struct Node *NodePtr; allows this:
NodePtr a, b; // declares two Node*; both (a) and (b)
If you spend enough time writing code in C the former of these will come back to bite you enough times you learn to not make that mistake, but it can still happen once in awhile.
The Load Loop
Regarding the load-loop for piecing together your list, you're not wiring up your list correctly, and frankly there are a million ways to do it, one being the one below. This does not require you to clean out "an extra node". Nor does it require any if (head){} else{} block structure to avoid said-same condition. Consider what we're really trying to do: create nodes and assign their addresses to the right pointers:
NodePtr head = NULL; // always the head of the list.
NodePtr* ptr = &head; // will always point to the next pointer to assign.
int n;
while (cin >> n)
{
*ptr = new Node;
(*ptr)->x = n;
ptr = &(*ptr)->next;
}
// note this always terminates the load with a NULL tail.
(*ptr)->next = NULL;
How It Works
Initialize the head pointer to NULL
Initializer a Node pointer-pointer (yes a pointer to a pointer) to point to the head pointer. This pointer-to-pointer will always hold the address of the target pointer that is to receive the address of the next dynamic-allocated node. Initially, that will be the head pointer. In the above code, this pointer-to-pointer is the variable: ptr.
Begin the while-loop. For each value read, allocate a new node, saving it in the pointer that is pointed-to by ptr (thus the *ptr). On the first iteration this holds the address of the head pointer, so the head variable will get our new node allocation. On all subsequent iterations, it contains the address of the next pointer of the last node inserted. Incidentally, saving the address of this new target pointer is the last thing that is done in the loop before we move to the next allocation cycle.
Once the loop is complete, the last node inserted needs to have its next pointer set to NULL to ensure a properly terminated linked list. This is mandatory. We conveniently have a pointer to that pointer (the same one we've been using all this time), and thus we set the pointer it "points to" to NULL. Our list is terminated and our load is complete. Brain Food: What pointer will it be pointing to if the load loop never loaded any nodes? Answer: &head, which is exactly what we want (a NULL head pointer) if our list is empty.
Design
I hope this will help better explain how it works through three full iterations of the loop.
Initial configuration
head ===> NULL;
ptr --^
After one iteration:
head ===> node(1)
next
ptr ------^
After two iterations
head ===> node(1)
next ===> node(2)
next
ptr ----------------^
After three iterations
head ===> node(1)
next ===> node(2)
next ===> node(3)
next
ptr --------------------------^
If we stopped at three iterations, the final termination assignment (*ptr = NULL;), gives:
head ===> node(1)
next ===> node(2)
next ===> node(3)
next ===> NULL;
ptr --------------------------^
Notice that head never changes once the first iteration is finished (it always points to the first node). Also notice that ptr always holds the address of the next pointer that is to be populated, which after the initial iteration (where it started as the address of our head pointer), will always be the address of the next pointer in the last node added.
I hope that gives you some ideas. It is worth noting that pairing these two pointers (the head pointer and the ptr pointer) into their own structure and having the appropriate management functions defines the textbook Queue; where one end is only for insertions (ptr) one is for extractions (head) and the container does not allow random access. There isn't much need for such a thing these days with the standard library container adapters like std::queue<>, but it does provide an interesting adventure into a good use of pointer-to-pointer concepts.
Complete Working Sample
This sample just loads our queue with 20 elements, prints them, then cleans out the queue and exits. Adapt to your usage as needed (hint: like change the source of the incoming data perhaps)
#include <iostream>
using namespace std;
// declare NodePtr as a pointer to Node, currently an incomplete type
// C and C++ both allow you to declare a pointer to damn-near anything
// so long as there is an understanding of what it *will* be, in this
// case, a structure called Node.
typedef struct Node *NodePtr;
// Now declare the structure type itself
struct Node
{
int x;
NodePtr next;
};
int main()
{
// load our list with 20 elements
NodePtr head = NULL;
NodePtr* ptr = &head;
for (int n=1;n<=20;++n)
{
*ptr = new Node;
(*ptr)->x = n;
ptr = &(*ptr)->next;
}
// terminate the list.
*ptr = NULL;
// walk the list, printing each element
NodePtr p = head;
while (p)
{
cout << p->x << ' ';
p = p->next;
}
cout << endl;
// free the list
while (head)
{
NodePtr victim = head;
head = head->next;
delete victim;
}
return 0;
}
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
You do not actually set the 'head' variable beyond NULL(head = ptr). You you actually lose your list from the get go. Try this:
int n;
NodePtr head, ptr;
ptr = new Node;
head = ptr;
while (cin >> n){
ptr->x = n;
ptr->next = new Node;
ptr = ptr->next;
}
You may then want to delete the last ptr->next and set it to 0 to save memory and avoid printing out an extra value.
First, your typedef : typedef struct Node; is not correct. You declare a struct with the sintaxe:
struct st_Name{
int field1;
double field2;
};
Typedef is like a name attribution function. You should (for easier reading/working) change the name of your struct, wich is possible, after declaring it, with:
typedef struct Node_st Node;
Or, all in one statement:
typedef struct node_st{
int x;
struct node_st *next;
}Node;
In the segment above, notice that I also changed the NodePtr to struct node_st *Next for a reason: If you do all in one segment, since c++ code is read linearly top->down(kinda), if you try to make NodePtr a pointer to Node before the struct declaration you'll get an error, and if you do it later and use NodePtr inside the struct you'll also have an error.
The compiler don't know yet that the struct exists so it will say that you're trying to name something that does not exist.
Then, your pointers manipulation is wrong.
...
while (cin >> n){
ptr = new Node;
ptr->x = n;
ptr->next = NULL; // You're making the next slot inexistent/NULL
ptr = ptr->next; // You're just setting ptr to NULL
}
...
What I think that you want is to keep adding to the end a keep the head in the first number. You can do this simply with an if/else statement for the first case:
while (cin >> n){
if(head == NULL){
ptr = new Node;
ptr->x = n;
ptr->next = NULL;
head = ptr;
}else{
ptr->next = new Node;
ptr = ptr->next;
ptr->x = n;
ptr->next = NULL;
}
}
This way, your insertion happens in the end so your print loop should work.
Hope this helps.
You aren't connecting the list. Every new item will have it's ->next NULL.
You say ptr = ptr->next (which is NULL) but then the next iteration overwrites ptr with the newly allocated node. You need to rearrange your code to string the nodes together...
One way of doing that is ptr->next = head makes your new node point to the old head.
Then head = ptr to move the head to the new node. e.g.:
To insert in the beginning (e.g. for a LIFO, last-in-first-out):
while (cin >> n){
ptr = new Node;
ptr->x = n;
ptr->next = head;
head = ptr;
}
To insert at the end (for a FIFO):
while (cin >> n){
if(!head) {
head = new Node;
ptr = head;
}
else
{
ptr->next = new Node;
ptr = ptr->next;
}
ptr->next = NULL;
ptr->x = n;
}