P
P
Philip Polikarenkov2017-03-20 18:18:59
Programming
Philip Polikarenkov, 2017-03-20 18:18:59

How to add multiple nodes in singly linked lists in C?

I can't figure out how to add a node to the list in a loop. Internet dug, what I found - did not help.
The algorithm I have developed is something like this:
1. I create a structure with a link and a field for storing data (for example, the int type)
2. I create a pointer to the structure.
3. I allocate memory with the malloc command.
4. I put the data in the data field.
5. I equate the pointer to NULL.
When adding a node, I also create a node, and set the pointer of the first node to the newly created one.
Actually, I don’t understand what is the dynamism of lists if, when creating a node, I need to give a name to the node. It turns out that I need to know in advance how many nodes I need?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Pozharsky, 2017-03-20
@Vilibb

"Actually, I do not understand what is the dynamism of lists, if when creating a node I need to give a name to the node"
And what kind of name?
The point is the following.
For an array, you need to know in advance how much memory to allocate.
For a list, you can add elements on the go (for example, in a cycle of unknown duration).
Conditionally:

struct List {
  void* value;
  List* next;
}

List* newList(void* value) {
  List* result = malloc(sizeof(List), 1);
  result->value = value;
  result->next = NULL;
  return result;
}

void main() {
  char* rootValue = "ROOT";
  List* root = newList((void*)rootValue);
  List* list = root;
  while(true) {
    char* value = input();
    if (streq(value, "BREAK")) {
      break;
    }
    list->next = newList((void*) value);
    list = list->next;
  }
  list = root;
  while(list != NULL) {
    printf("%s", (char*)list->value);
    list = list->next;
  }
}

K
kzoper, 2018-01-17
@kzoper

Will it fit?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question