Why do so many examples of linked lists put the next pointer at the end of each node, and not at the beginning?

I have seen quite a few examples of implementing C linked lists on this site, and most of them put the following pointer at the end of each node, like this ...

struct intNode1 {
   int data;
   intNode1 *next;
};

Why do they implement them like this instead?

struct node {
   struct node *next;
};

struct intNode2 {
   struct node node;
   int data;
};

The last way to implement linked lists allows your insert and delete code to work with any type of node, and it also allows you to create a general type of list, while the previous way forces you to implement each kind of list from scratch.

For example, here is a (incomplete) implementation of a singly linked list using both types of nodes:

struct intList {
   struct intNode1 *head;
};

struct list {
   struct node *head;
};

, , , , , . :

/* Returns zero if successful or nonzero otherwise */
int list-insertInt(struct list *list, int n) {
   struct intNode2 * newNode;
   if(!(newNode = malloc(sizeof *newNode)) {
      return -1;
   }
   newNode->data = n;
   return list-insertNode(list, (struct node *)newNode);
}

/* Assumes that the list contains only int nodes. */
int list-containsInt(struct list *list, int n) {
   struct intNode2 *current = (intNode2 *)list->head;
   while (current) {
      if(current->data == n) {
         return true;
      }
      current = current->next;
   }
   return false;
}

, , free , , :

void list-free(struct list *list) {
   struct node *current = list->head;
   struct node *next;
   while(current) {
      next = current->next;
      free(current);
      current = next;
   }
}

PS. (.. , ), . , .

+3
4

. "" . , , ...

+5

, , , ( prev, ).

, node .

+1

, node . , , ANSI C. , , .

, , ( !).

+1

Next , - . .

Honestly, I'm not sure if I ever came across a situation in C where the linked list supported different types of node. But doing what you described could be used if that is what you needed to do.

Note that most C programmers today use C ++, which allows you to use inheritance to achieve the same. Using inheritance, it doesn't matter where the Next member was placed in the class.

0
source

Source: https://habr.com/ru/post/1796639/


All Articles