C语言实现链表的生成、删除、插入
讲解视频
/*
* Author: Mingchong Li
* Email: 19726006@bjtu.edu.cn
* Date: 2022/1/8
*/
#include <stdio.h>
#include <stdlib.h>
/* Define the node
* If we don't use `typedef` here,
* we have to call it `struct nodes` instead of `node`.
*/
typedef struct nodes {
int num; // store data
struct nodes *next; // point to the next node
} node; // here we can define other names of node
/*
* Create the a link list for the given array.
* int x[]: given an integer array
* int n: preset the size of array
*/
node *create(int x[], int n) {
// the head will return at last
node *head = (node *) malloc(sizeof(node));
if (n == 0) {
return NULL; // if here is an empty array
}
head->num = x[0]; // the first num
head->next = NULL; // if the array is size of 1, the head will be the tail
node *p = head; // p is an "allocator", allocate nums from the next of head
for (int i = 1; i < n; i++) {
p->next = (node *) malloc(sizeof(node)); // store in heap
p->next->num = x[i]; // store the num
p = p->next; // go to the next
p->next = NULL; // if it is the end, then next is NULL
}
return head;
}
/*
* display all of the node's num
*/
void display(const node *head) {
const node *p = head;
for (; p != NULL; p = p->next) {
printf("%d ", p->num); // print until NULL
}
printf("\n");
}
/*
* insert x to the head on n
* n < 0 or n >= size of link list will return
*/
void insert(node *head, int x, int n) {
node *p = head;
if (n == 0) {
// the head will be copied and insert to the next of head
insert(head, head->num, 1);
// change the num of head to x
head->num = x;
return;
} else if (n < 0)
return;
// locate to the pre one of n
for (int i = 0; i < n - 1; i++) {
p = p->next;
if (p == NULL)
return;
}
node *preNext = p->next;
p->next = (node *) malloc(sizeof(node));
p->next->num = x;
p->next->next = preNext;
}
/*
* delete the node position on n
*/
void delete(node *head, int n) {
node *p = head;
// we can't delete the head, for the pointer to head couldn't be changed
// so we just copy the next one to head, and delete the next one
if (n == 0) {
p->num = p->next->num;
delete(head, 1);
}
for (int i = 0; i < n - 1; i++) {
p = p->next;
if (p == NULL)
return;
}
p->next = p->next->next; // delete
}
int main() {
int arr[] = {1, 3, 5, 7, 9};
node *linkList = create(arr, sizeof(arr) / sizeof(int));
display(linkList);
insert(linkList, 0, 0);
display(linkList);
delete(linkList, 0);
display(linkList);
free(linkList); // free heap
return 0;
}