### Trying to understand C++ Linked List

I'm fairly new to C++ and just started going over more advanced data structures. This weeks homework was about Linked Lists. I understand the concept but am still fairly lost when it comes to implementing it. Here was one of the questions from my assignment. If you could explain the reasoning behind answering it I would really appreciate it! Thanks!!

Assume that the node of a linked list is in the usual info->link form with the info of type int (list and ptr are pointers of type nodeType). The following code creates a linked list. Determine the following:

1) Which pointers points to the first node of the linked list?
2) Determine the order of the nodes of the linked list

ptr = new nodeType;
ptr->info = 16;
list = new nodeType;
list->info = 25;
ptr = new nodeType;
ptr->info = 12;
- Unless those encompass multiple instances of a function call, you cannot(as far as i know) allocate space to ptr for a nodeType object, as it has already been done.

- Additionally, Is this in any type of order, or do these lines of code directly follow one another?

- I'm not sure how this was presented to you in the problem, so i'm not sure of what answer to give you.
 ``12345678910111213141516171819202122232425262728293031`` ``````#include struct nodeType { int info ; nodeType* link ; }; int main() { nodeType* ptr ; nodeType* list ; ptr = new nodeType; ptr->info = 16; list = new nodeType; list->info = 25; list->link = ptr; ptr = new nodeType; ptr->info = 12; ptr->link = NULL; list->link->link = ptr; unsigned count = 1 ; ptr = list ; while ( ptr ) { std::cout << "Node #" << count++ << ':' << ptr->info << '\n' ; ptr = ptr->link ; } }`````` ```Node #1:25 Node #2:16 Node #3:12```

And, of course, corresponding deletes for the news would be recommended.
Last edited on
- Well, if it's presented the way circe has it then i can explian it for you.

- ptr and list first have space allocated for them, then you basically set the link pointer of list(the node with 25 as it's value) to point to the address of ptr(the node with 16 as it's value).

- Then you allocate space for another Node object, and you set the link pointer for that object to null as it is going to be at the end.

- Then you proceed to make the link pointer of the node object after list point to the new ptr (the node with 12 as it's value).

- I hope that made some type of sense.
Last edited on
Thanks everyone for the help! Especially Cire and thejman250!!! The code example helped a lot and thejman250's step by step explanation cleared up some of the confusion I had.
Topic archived. No new replies allowed.