Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
566 views
in Technique[技术] by (71.8m points)

I don't understand the implementation of inserting a new node in linked list

In linked list implementation, the insertion of a new node to the linked list is usually written like this:

void push(struct node** head_ref, int new_data)

/* 1. allocate node */
struct node* new_node = (struct node*) malloc(sizeof(struct node));

/* 2. put in the data  */
new_node->data  = new_data;

/* 3. Make next of new node as head */
new_node->next = (*head_ref);

/* 4. move the head to point to the new node */
(*head_ref)    = new_node;

(I took this code from http://quiz.geeksforgeeks.org/linked-list-set-2-inserting-a-node/)

and the node struct is:

struct node {

int data;

struct node *next;

};

What I don't understand is the 3. and 4. of the insertion part. So you make the next pointer of new_node pointed to the head, and then the head points to the new_node? So that means the next pointer points to new_node?

It seems like a stupid question but I'm having trouble understanding it, so I hope someone can explain it to me. Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Well basically in a linked list all nodes are connected to each other. It depends upon u that where do u insert a new node either at end or start. Each time we insert a new node we will check the head pointer.

   if(head == NULL)  //it means that the node is empty
   {
      head = newNode;  //so we will assign the new node to the head
   }
    else
   {
      node* temp = head;       //creating a temp pointer that will go 
                               // to the end of the linked list

      while(temp -> next != NULL) { temp = temp->next; }
      temp = newNode;          //This will add the new node to the end
      newNode->next = NULL;enter code here 
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...