简体   繁体   中英

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. it justs asks for the next node in the first Cell - so how can this work?

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. It doesn't need to manipulate second (assuming its a singly linked list).

It's a recursive algorithm that walks until the end of the first list (the else branch); 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.

The else block of the function keeps following the next pointer of first until it gets to the end of that list. That is, until first->next is NULL and the else does not get executed.

Now the base case in the if block. When first->next is NULL , it changes that pointer to point at second , which is presumably the first element in another list.

The reason there is some effect is because the first->next pointer is passed by reference. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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