Chained tables are a basic lesson in C, but it's fun to implement them.

Define the structure

#include <malloc.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct {
			  int data;
			  struct Node *pNext;
} Node;

constructor

Why write this, because each manual malloc will be redundant, borrowed from the C++ new

Classic interview question, the difference between new and malloc

but cpp suggests using unique_ptr instead of bare pointers

About malloc without type conversion

Do I cast the result of malloc?

Node *mkNode(int value, Node *pNext)
{
			  Node *pNode = malloc(sizeof(Node));
			  if (pNode == NULL)
				{
						    printf("分配失败程序退出!");
						    exit(-1);
			  }
			  pNode->data = value;
			  pNode->pNext = pNext;
			  return pNode;
};

Constructing a linked table

Node *rec_create_list_from_arr(int *arr, size_t len, size_t i)
{
			  if (i == len)
						    return NULL;
			  return mkNode(arr[i], rec_create_list_from_arr(arr, len, i + 1));
}

Print the linked table

void TraverseList(Node *pHead)
{
			  if (pHead == NULL)
						    return;
			  printf("%d", pHead->data);
			  TraverseList(pHead->pNext);
}

nth

Node *nth_node(Node *node, int n)
{
				if (node == NULL)
						    return NULL;
			  if (n == 0)
						    return node;
			  return nth_node(node->pNext, n - 1);
}

join_list

void join_list(Node *tail, Node *head)
{
			  tail->pNext = head;
}

Insert node after