我不了解在链表中插入新节点的实现 [英] I don't understand the implementation of inserting a new node in linked list

查看:38
本文介绍了我不了解在链表中插入新节点的实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在链表实现中,向链表插入一个新节点通常是这样写的:

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

void push(结构节点** head_ref,int new_data)

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;

(我从 http://quiz.geeksforgeeks.org/linked-list-set-2-inserting-a-node/)

节点结构是:

结构节点{

int数据;

结构节点*next;

};

我不理解的是插入部分的3.和4..因此,您使new_node的下一个指针指向头部,然后头部指向new_node?所以这意味着下一个指针指向new_node?

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.

推荐答案

基本上在一个链表中所有节点都是相互连接的.取决于您,您要在末尾还是起始处在哪里插入新节点.每次插入新节点时,我们都会检查头指针.

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 
    }

这篇关于我不了解在链表中插入新节点的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆