简体   繁体   English

链表-使用后部指针末尾插入

[英]Linked list - Insert at end using a rear pointer

I'm learning about linked list insertions and encountered the following code to insert a node at the end of a linked list (in a rather old and obsolete book for C++ still used I don't know why): 我正在学习有关链表插入的知识,并遇到了以下代码,以便在链表的末尾插入一个节点(在C ++仍然使用的一本相当陈旧且过时的书中,我不知道为什么):

void Insert_End(Node * np){
    if (start == NULL){
        start = rear = np;
    }
    else{
        rear -> next = np;
        rear = np;
    }
}

My question is shouldn't it be np -> next = rear; 我的问题是不应该是np-> next = Rear;

PS : np is the new node being inserted at the end, rear points to the last node, start points to the first node. PS:np是在末端插入的新节点,后方指向最后一个节点,起点指向第一个节点。

My question is shouldn't it be np -> next = rear; 我的问题是不应该是np-> next = Rear;

No,following pictures may help you understand easily. 不,下面的图片可以帮助您轻松理解。

When you do start = rear = np; 当您start = rear = np; for the first time all the 3 nodes may look like below. 第一次,所有3个节点可能如下所示。

  ------
  |  np  |
   ------
  ^      ^
  |       |
 ----      ----
|start|   | rear|
 ----      ----

for the successive insertion: 对于连续插入:

when you do rear -> next = np; 当您进行rear -> next = np; your list may look like below. 您的列表可能如下所示。

note: rear is still pointing to previous last node of the list and np1 is pointing to np2 . 注意: rear仍然指向列表的上一个最后一个节点, np1指向np2

  ------         -----
  |  np1 | ---> | np2 |
   ------        -----
  ^       ^
  |       |
 ----      ----
|start|   | rear|
 ----      ----

when you do rear = np; 当你做rear = np; your rear gets updated to point current last node. 您的rear将更新为指向当前的最后一个节点。

  ------         -----
  |  np1 | ---> | np2 |
   ------        -----
  ^              ^
  |              |
 ----           ----
|start|        | rear|
 ----           ----

My question is shouldn't it be np -> next = rear; 我的问题是不应该是np-> next = Rear;

No, because then no node would be pointing to np , and therefore it wouldn't be part of any list (other than the list whose head is np ). 不可以,因为这样就不会有节点指向np ,因此它不会成为任何列表的一部分(头为np的列表除外)。 Furthermore, np wouldn't be at the rear, since its next would be pointing at a node (the node that was rear previously). 此外, np不会在后面,因为它的next将指向一个节点(之前位于rear的节点)。 The example is a correct implementation. 该示例是正确的实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM