Linked list

I am trying to understand how to implement one. Maybe I just don't understand pointers here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>

using namespace std;

struct Node
{
    int data;
    Node *next;

};

int main()
{
    Node *n;
    Node *temp; 
    Node *head;//pointer to head node

    n = new Node;
    n->data = 1;
    temp= n;
    head = n;

    n = new Node;
    h -> data = 2;

    temp ->next =n;
    temp = temp->next;

    n->next = NULL;
}


Why is this necessary?

 
    t = t->next;


I thought that the code before it handled where t was pointed to.

I realize that this isn't the best implementation and was wondering for a good book or tutorial to really learn how to make and implement linked list.

Last edited on
The important question is: What is the logical purpose of each variable?

For example, what do the h and t represent? Are those names descriptive?


You know struct, Do you also know about class constructors? If your struct Node would have a constructor, then your other code would be simpler and you might avoid some mistakes too.
I do know about classes. It's just that the particular example I was looking at used a struct and presented it this way.
In that example, it isn't necessary because nothing ever uses the list. It is moving the temp to point to the second node. There are hundreds if not thousands of examples of linked lists on the internet. In fact if you google for it you'll actually see some useful examples that actually use one after building it. There isn't much to learn from that example.
Topic archived. No new replies allowed.