1

I still can't figure out how HEAD in linked list works.

What type of data is head? How can head be linked (connected) to the first note?

That is what I have written, but still, don not know how to implement head.

typedef struct node 
{

    int val;
    struct node* next;
}
node;

int main()
{
// dynamically allocate memory for 2 nodes
node* node1 = malloc (sizeof(node));
node* node2 = malloc (sizeof(node));

// set each value
node1 -> val = 10;
node2 -> val = 20;

// link node1 with node2
node1 -> next = node2;  

    return 0;
}

Any help is appreciated.

1 Answer 1

2

Your question is unclear, but I'll take a shot at it. In a linked list, HEAD is usually a var name, not a data type. HEAD is usually a pointer or possibly a data structure that serves as the pointer to the first element in the linked list.

In your code, node1 serves as a head. However, if you wanted to insert a new node at the beginning of the list, you'd have to remember that it is the new head.

Additionally, the method that you are using requires naming every node. The common way to implement a linked list of nodes is to create nodes that are not stored in named variables, but have their addresses stored in a pointer in the previous node.

For example, in your code, you'd add a head var to point at the head of the list and create nodes as needed:

node* head = NULL;  // create the head with no content.
head = malloc(sizeof(node));   // creates memory space for the head node
//the previous two lines can be combined.

head->next = malloc(sizeof(node));   //adds the next node

node* temp = NULL;   //creates a temp var for moving through the list.
// you don't want to change head when walking through the list.
// if you insert a node at the front of the list, then you would update head

There's more, but that's all covered in lectures and shorts.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

2
  • I thought, that head is a pointer to the first element in the list, just a pointer. So head can not have any data (head -> val) to store. But if I declare like this node* head head will have a data to store and a pointer to the next element. So, now I use head as a typical node, but, keep in mind that this node is first and call it "head". Am I right? Commented May 2, 2017 at 22:35
  • Yes. Head is a pointer to the first element, and that element is a full node. Similarly, that node's next element is a pointer to a node, and so on. Now, try and wrap your head around this. The address of the third node is stored in head->next->next. Happy coding! ;-)
    – Cliff B
    Commented May 2, 2017 at 23:40

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .