AlldaRage
AlldaRage

Reputation: 121

trying to understand this linkedlist insertion code

i have this code

struct Node {
   int data;
   struct *Node next;
};

struct Node *head;

void insert(int x) {
    node* temp = (node*)malloc(sizeof(struct node));
    temp->data = x;
    temp->next = head;
    head = temp;
}

int main()
{
     head = NULL;
}

I'm following this video, It looks like the code works. I'm having a hard time putting it together though.

we have a node head which is initially set to NULL in the main method.

The linkedlist holds an int and next. This insert code sets data to an int and next to head. Then it sets head to temp.

Wouldn't this make give head the int and then make it point to itself over and over again since we set temp.next to head and then head = temp ?

So far I've only done iterations on linkedlist where the last next is NULL.

Upvotes: 0

Views: 55

Answers (2)

Paul Roub
Paul Roub

Reputation: 36438

No.

node* temp = malloc(sizeof(struct node));
temp->data = x;

We have a new node, and have set its value.

temp->next = head;

The head (if any) will come after this element in the list. That means this should be our new head.

head = temp;

And now it is.

If head was NULL, this list has no next entry, as expected.

If head was not NULL, this node is the new head, and its next points to the second element in the list (the old head).

Upvotes: 0

Mureinik
Mureinik

Reputation: 311018

This code inserts an item at the beginning of a linked list - it creates a new node, sets its data, and makes its next point to the current head.

Upvotes: 0

Related Questions