K
K
KagelBull2020-08-11 11:12:49
C++ / C#
KagelBull, 2020-08-11 11:12:49

What is the purpose of this function for a singly linked list?

What is the purpose of the f function? I just realized that it adds a node to a singly linked list. But where it adds is not clear, whether a new root node is being created, or something else.
Specifically, the last line of the *s=el function is not clear;

struct A{
  int info;
  struct A *next;
};

void f(struct A **s, int i)
{
  struct A *el;
  el = (struct A*)malloc(sizeof(struct A));
  el->info = i;
  el->next = *s;
  *s=el;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
AnT, 2020-08-11
@KagelBull

The function adds a new element to the beginning of the singly linked list and updates the pointer to the beginning of the list accordingly. It is the updating of the pointer to the beginning of the list that is done through the assignment *s = el.
This function can also be used to insert an element in the middle of the list if a spointer to the field of the nextprevious element is passed as a parameter. (In other words, inserting an element in the middle of the list is nothing more than inserting an element at the beginning of the right sublist starting at the insertion point.)
PS The function is written stylistically crooked: it does an unnecessary type cast on the result mallocand does not take advantage of the obvious opportunity to perform variable initialization el( instead of assignment).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question