简体   繁体   English

C ++:递归地附加链表

[英]C++: Appending linked list recursively

This code is supposed to append two linked lists, I totally fail to see how this code appends the two Cell Structs passed as arguments, as no manipulating is happening to the second parameter. 这段代码应该附加两个链接列表,我完全看不出这个代码如何附加作为参数传递的两个Cell Structs,因为没有对第二个参数进行操作。 it justs asks for the next node in the first Cell - so how can this work? 它只是要求第一个Cell中的下一个节点 - 所以它如何工作?

void Append(Cell *& first, Cell* second)
{
  if (first == NULL)
  {
    first = second;
  }
else {
    Append(first->next, second);
  }
}

It recurses until first is a reference to the next pointer of the last Cell in the first list, which it sets to point to the first Cell in the second. 它会递归直到first是对第一个列表中最后一个Cellnext指针的引用,它设置为指向第二个Cell中的第一个Cell It doesn't need to manipulate second (assuming its a singly linked list). 它不需要操纵second (假设它是一个单链表)。

It's a recursive algorithm that walks until the end of the first list (the else branch); 它是一个递归算法,一直走到第一个列表的末尾( else分支); once the end has been found ( first==NULL ), the first element of the second list is linked to the last element of the first one, obtaining a list that is the concatenation of the two original lists. 一旦找到结束( first==NULL ),第二个列表的第一个元素将链接到第一个元素的最后一个元素,获得一个列表,该列表是两个原始列表的串联。

The else block of the function keeps following the next pointer of first until it gets to the end of that list. else功能块会继续跟随next的指针first ,直到它到达该列表的末尾。 That is, until first->next is NULL and the else does not get executed. 也就是说,直到first->nextNULL并且else不会被执行。

Now the base case in the if block. 现在if块中的基本情况。 When first->next is NULL , it changes that pointer to point at second , which is presumably the first element in another list. first->nextNULL ,它将指针更改为指向second ,这可能是另一个列表中的第一个元素。

The reason there is some effect is because the first->next pointer is passed by reference. 有一些影响的原因是因为first->next指针是通过引用传递的。 Modifying the pointer will modify the actual pointer at the end of the list, rather than just modifying a copy. 修改指针将修改列表末尾的实际指针,而不是仅修改副本。

The second list does not need to be modified. 第二个列表不需要修改。 The code will recursively traverse the first list until it reaches the last element in the first list and set that element's next pointer to the start of the second list. 代码将递归遍历第一个列表,直到它到达第一个列表中的最后一个元素,并将该元素的下一个指针设置为第二个列表的开头。 The elements in the second list will be shared by both lists. 第二个列表中的元素将由两个列表共享。

before: 之前:

first → a → b → c

second → d → e → f

after: 后:

first → a → b → c
                ↓
second →        d → e → f

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

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