2023-01-11 00:48:48 +08:00
|
|
|
/**
|
|
|
|
* File: list_node.h
|
|
|
|
* Created Time: 2023-01-09
|
|
|
|
* Author: Reanon (793584285@qq.com)
|
|
|
|
*/
|
2023-04-27 01:18:18 +08:00
|
|
|
|
2023-01-11 00:48:48 +08:00
|
|
|
#ifndef LIST_NODE_H
|
|
|
|
#define LIST_NODE_H
|
|
|
|
|
|
|
|
#ifdef __cplusplus
|
|
|
|
extern "C" {
|
|
|
|
#endif
|
|
|
|
|
2023-04-09 04:32:17 +08:00
|
|
|
/* 链表节点结构体 */
|
2023-10-18 02:16:26 +08:00
|
|
|
typedef struct ListNode {
|
2023-04-09 04:32:17 +08:00
|
|
|
int val; // 节点值
|
2023-08-17 05:13:19 +08:00
|
|
|
struct ListNode *next; // 指向下一节点的引用
|
2023-10-18 02:16:26 +08:00
|
|
|
} ListNode;
|
2023-01-11 00:48:48 +08:00
|
|
|
|
2023-04-09 04:32:17 +08:00
|
|
|
/* 构造函数,初始化一个新节点 */
|
2023-01-12 00:31:11 +08:00
|
|
|
ListNode *newListNode(int val) {
|
2023-10-29 00:09:54 +08:00
|
|
|
ListNode *node;
|
2023-04-17 21:13:15 +08:00
|
|
|
node = (ListNode *)malloc(sizeof(ListNode));
|
2023-01-11 00:48:48 +08:00
|
|
|
node->val = val;
|
|
|
|
node->next = NULL;
|
|
|
|
return node;
|
|
|
|
}
|
|
|
|
|
2023-10-27 01:04:17 +08:00
|
|
|
/* Generate a linked list with an array */
|
2023-01-12 00:31:11 +08:00
|
|
|
ListNode *arrToLinkedList(const int *arr, size_t size) {
|
2023-01-11 00:48:48 +08:00
|
|
|
if (size <= 0) {
|
|
|
|
return NULL;
|
|
|
|
}
|
|
|
|
|
2023-01-12 00:31:11 +08:00
|
|
|
ListNode *dummy = newListNode(0);
|
2023-01-11 00:48:48 +08:00
|
|
|
ListNode *node = dummy;
|
|
|
|
for (int i = 0; i < size; i++) {
|
2023-01-12 00:31:11 +08:00
|
|
|
node->next = newListNode(arr[i]);
|
2023-01-11 00:48:48 +08:00
|
|
|
node = node->next;
|
|
|
|
}
|
|
|
|
return dummy->next;
|
|
|
|
}
|
|
|
|
|
2023-04-17 22:15:06 +08:00
|
|
|
/* Get a list node with specific value from a linked list */
|
2023-01-12 00:31:11 +08:00
|
|
|
ListNode *getListNode(ListNode *head, int val) {
|
2023-01-11 00:48:48 +08:00
|
|
|
while (head != NULL && head->val != val) {
|
|
|
|
head = head->next;
|
|
|
|
}
|
|
|
|
return head;
|
|
|
|
}
|
|
|
|
|
2023-11-01 05:14:22 +08:00
|
|
|
/* Free the memory allocated to a linked list */
|
|
|
|
void freeMemoryLinkedList(ListNode *cur) {
|
|
|
|
// 释放内存
|
|
|
|
ListNode *pre;
|
|
|
|
while (cur != NULL) {
|
|
|
|
pre = cur;
|
|
|
|
cur = cur->next;
|
|
|
|
free(pre);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-01-11 00:48:48 +08:00
|
|
|
#ifdef __cplusplus
|
|
|
|
}
|
|
|
|
#endif
|
|
|
|
|
2023-10-18 02:16:26 +08:00
|
|
|
#endif // LIST_NODE_H
|