单链表
C语言实现
涉及二级指针内存申请和释放
结构体定义
typedef int32_t DATA_TYPE;
typedef struct {
DATA_TYPE value;
struct List *next;
} List;
相关方法实现
#include <stdio.h>
#include <stdbool.h>
#include <inttypes.h>
#include <malloc.h>
/**
* 创建一个链表,头节点为第零个节点
* @param head 二级指针 函数内部分配内存
* @param length 链表长度
*/
void create_list(List **head, int32_t length) {
*head = (List *) malloc(sizeof(List));
(*head)->next = NULL;
List *cur = NULL;
// 头插法创建链表
for (int i = 0; i < length; i++) {
cur = (List *) malloc(sizeof(List));
cur->value = i + 1;
cur->next = (*head)->next;
(*head)->next = (struct List *) cur;
}
}
/**
* 在index位置后插入一个节点
* @param head
* @param index
* @param data
* @return
*/
int insert_element(List *head, int index, DATA_TYPE data) {
if (!head) {
return -1;
}
int cur = 1;
List *cur_ptr = (List *) head->next;
while (cur_ptr && cur < index) {
cur_ptr = (List *) cur_ptr->next;
++cur;
}
if (!cur_ptr || cur > index) {
return -1;
}
List *node = (List *) malloc(sizeof(List));
node->value = data;
node->next = cur_ptr->next;
cur_ptr->next = (struct List *) node;
return 0;
}
int delete_element(List *head, int index, DATA_TYPE *data) {
if (!head) {
return -1;
}
int cur = 1;
List *cur_ptr = (List *) head->next;
while (cur_ptr && cur < index) {
cur_ptr = (List *) cur_ptr->next;
++cur;
}
if (!cur_ptr || cur > index) {
return -1;
}
List *q = NULL;
q = (List *) cur_ptr->next;
cur_ptr->next = q->next;
*data = q->value;
free(q);
return 0;
}
int32_t get_element(List *head, int32_t index, DATA_TYPE *data) {
int cur = 0;
List *cur_ptr = (List *) head->next;
while (cur_ptr && cur != index) {
cur_ptr = (List *) cur_ptr->next;
++cur;
}
if (!cur_ptr || cur > index) {
return -1;
}
*data = cur_ptr->value;
return 0;
}
int get_size(List *head) {
if (!head) { return -1; }
int size = 0;
List *cur = head;
while (cur != NULL) {
cur = (List *) cur->next;
size++;
}
return size;
}
int main() {
// 链表初始化
List *head;
create_list(&head, 10);
int num;
get_element(head, 2, &num);
insert_element(head, 2, 100);
delete_element(head, 1, &num);
int size = get_size(head);
for (int i = 0; i < size; ++i) {
printf("%d ", head->value);
head = (List *) head->next;
}
// 二级指针申请内存,函数外释放
free(head);
}