I have a question about the search function. A pointer is created in the main program Node *a = NULL; where the address of the next most recently created "trailer" is written. And when the add function finishes creating a chain, it will return a pointer to the last "trailer". And then the Find function is called. And how can it do a search if the address of the last element of the chain, but not the first one, was passed? Therefore, I do not understand why head = head->next; Don't stick everything in null. Where did I go in the wrong direction?

  struct Node { int Data; Node* next; }; Node* add(Node *head, int Value) { Node *New = (Node*) malloc(sizeof(Node)); New->Data = Value; New->next = head; return New; } Node* Find(Node *head, int Value) { while (head) { if (head->Data == Value) return head; head = head->next; } return NULL; } int main() { Node *a = NULL; for (int i = 0; i < 5; i++) a = add(a, i); Node *del = Find(a, 2); 
  • You insert goes to the top of the list, but not at the end. To insert at the end, you need to go through the list to the end, then paste. - JaponDemon

1 answer 1

The add function always adds a new "trailer" to the very top of the list. With each call, it returns a pointer to the new beginning of the list. Thus, the a pointer always points to the very first “trailer” in the list, and not to the very last one, as you incorrectly think.

The Find function begins a search with a , that is, from the beginning of the list and scans the entire list to the end.

  • And what determines what it inserts at the top of the list? - Elvin
  • @Elvin: The implementation of the add function defines. There, in black and white implemented inset at the top of the list. - AnT
  • and so it should be that at the top of the list? And another question: is it all because of him? New-> next = head; - Elvin
  • one
    Because of him. They themselves wrote: assign the following New-> next = head; New set before the existing. - JaponDemon
  • one
    @Elvin, head is a pointer to the first item. You put this pointer in the next field of the new element. It turns out that the old first element becomes the second (following the new one). And the new element becomes the first. - insolor