在链表的末尾插入节点

时间:2022-01-20 07:17:57

Below fragment is invalid to inserting a node in the end of Linked List.

下面的片段无法在链接列表的末尾插入节点。

void insert_end(int item){

    nodeptr newNode = new ListNode;
    newNode->data = item;
    newNode->next = NULL;

    if(head == NULL){
        head = newNode;
        curr = head;

    }else{
        curr = head;

        while(curr != NULL) curr = curr->next;
        curr = newNode;
    }
}

Another fragment that is valid to inserting a node in the end of Linked List.

另一个有效插入链接列表末尾节点的片段。

void insert_end(int item){

    nodeptr newNode = new ListNode;
    newNode->data = item;
    newNode->next = NULL;

    if(head == NULL){
        head = newNode;
        curr = head;

    }else{
        curr = head;

        while(curr->next != NULL) curr = curr->next;

        curr->next = newNode;
    }
}

My question is why 1st one is invalid? Actually two fragments should be similar. Assume i have three nodes already. Now i want to inserting another node.

我的问题是为什么第一个无效?实际上两个片段应该是相似的。假设我已经有三个节点。现在我想插入另一个节点。

  1. As first algorithm when curr = NULL, then while loop will not satisfied.
  2. 作为curr = NULL时的第一个算法,则while循环将不满足。
  3. As second algorithm when curr->next = NULL then while loop will not satisfied.
  4. 作为第二个算法,当curr-> next = NULL时,while循环将不满足。

so can i say first algorithm's 'curr' and second algorithm 'curr->next' both are similar, when "while loop" terminated? if it's not similar then why?

所以我可以说第一个算法的'curr'和第二个算法'curr-> next'都是相似的,当“while loop”终止时?如果它不相似那么为什么呢?

1 个解决方案

#1


1  

You must understand a pointer is a variable which value is an address.

您必须了解指针是一个变量,其值是一个地址。

First algorithm is wrong because when you finish the iteration of while loop, curr points to NULL (address 0x0), and NULL is not a valid node of your list.

第一种算法是错误的,因为当你完成while循环的迭代时,curr指向NULL(地址0x0),而NULL不是列表的有效节点。

Second algoritm works because when you finish the iteration of while loop, curr points to last node of your list, and you add newNode to curr->next, replacing NULL by the address of newNode.

第二个算法有效,因为当你完成while循环的迭代时,curr指向列表的最后一个节点,然后你将newNode添加到curr-> next,用newNode的地址替换NULL。

Hope this helps! :)

希望这可以帮助! :)

#1


1  

You must understand a pointer is a variable which value is an address.

您必须了解指针是一个变量,其值是一个地址。

First algorithm is wrong because when you finish the iteration of while loop, curr points to NULL (address 0x0), and NULL is not a valid node of your list.

第一种算法是错误的,因为当你完成while循环的迭代时,curr指向NULL(地址0x0),而NULL不是列表的有效节点。

Second algoritm works because when you finish the iteration of while loop, curr points to last node of your list, and you add newNode to curr->next, replacing NULL by the address of newNode.

第二个算法有效,因为当你完成while循环的迭代时,curr指向列表的最后一个节点,然后你将newNode添加到curr-> next,用newNode的地址替换NULL。

Hope this helps! :)

希望这可以帮助! :)