U
U
uzi_no_uzi2020-04-16 15:34:26
C++ / C#
uzi_no_uzi, 2020-04-16 15:34:26

How does this feature work?

There is a code that has questions

#include <iostream>
#include <fstream>
using namespace std;

void insert(list*& p, char value); 
 
struct list
{
  char symbol;
  list* next;
};

int main()
{
  setlocale(LC_CTYPE, "Russian");
  list* first = nullptr;

  char value;
  cout << "Введите символ ";
  cin >> value;
  insert(first, value);
}

void insert(list*& p, char value) // 
{
  list* newP = new list;
  if (newP != NULL)     //есть ли место?  
  {
    newP->symbol = value;
    newP->next = p;
    p = newP;
  }
  else
    cout << "Операция добавления не выполнена" << endl;
}


1. The insert function takes two parameters, what is the first parameter for? Why pass a pointer to a link as the first parameter to the insert function?
2. list* first = nullptr - It looks like this line creates a pointer to the first element of a singly linked list, why assign emptiness to it?
3. What is going on in this line? list* newP = new list;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Shitskov, 2020-04-16
@Zarom

Questions should be asked to the developer of this code, because the general answer to all 3 points is because the code is written that way. The background is unknown.

  1. The first parameter is a reference to the "head of the list" pointer, the insert function creates a new list element and inserts it at the beginning, so it needs to change the value of pointers to the head
  2. "C++ implicitly converts nullptr to the appropriate pointer type." Void is assigned because it is empty, and variables should be initialized
  3. A new list item is created

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question