新节点成为头,而头成为新节点?

时间:2019-05-18 01:35:35

标签: c++ data-structures linked-list

   struct Node { 
      int data; 
      struct Node *next; 
      }; 
      struct Node* head = NULL;   
   void insert(int new_data) { 
       struct Node* new_node = (struct Node*) 
       malloc(sizeof(struct Node)); 
       new_node->data = new_data; 
       new_node->next = head; 
       head = new_node; 
      } 

有人可以用每行的插图解释此代码吗? 没有插图我无法理解 谢谢

1 个答案:

答案 0 :(得分:0)

struct Node{
int data;
struct Node *next;
}; // creates node with two field, one for integer data and another for node named next.

struct Node * head = NULL; //用null创建头节点

void insert(int new_data){//接受整数值的函数

struct Node* new_node = (struct Node*)
malloc(sizeof (struct Node));// creates Node "new_node" by dynamic allocation 
new_node->data = new_data;// accepted integer value is allocated to new_node's data field
new_node->next = head;// new_node's next is made to point head
head = new_node;// new node is made head.
}