hello-algo/codes/c/include/list_node.h

58 lines
1.2 KiB
C
Raw Normal View History

/**
* File: list_node.h
* Created Time: 2023-01-09
* Author: Reanon (793584285@qq.com)
*/
#ifndef LIST_NODE_H
#define LIST_NODE_H
#ifdef __cplusplus
extern "C" {
#endif
/* 链表节点结构体 */
struct ListNode {
int val; // 节点值
struct ListNode *next; // 指向下一节点的指针(引用)
};
2023-03-18 18:33:35 +08:00
// typedef 作用是为一种数据类型定义一个新名字
typedef struct ListNode ListNode;
/* 构造函数,初始化一个新节点 */
2023-01-12 00:31:11 +08:00
ListNode *newListNode(int val) {
ListNode *node, *next;
node = (ListNode *)malloc(sizeof(ListNode));
node->val = val;
node->next = NULL;
return node;
}
2023-04-17 22:15:06 +08:00
/* Generate a linked list with a vector */
2023-01-12 00:31:11 +08:00
ListNode *arrToLinkedList(const int *arr, size_t size) {
if (size <= 0) {
return NULL;
}
2023-01-12 00:31:11 +08:00
ListNode *dummy = newListNode(0);
ListNode *node = dummy;
for (int i = 0; i < size; i++) {
2023-01-12 00:31:11 +08:00
node->next = newListNode(arr[i]);
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) {
while (head != NULL && head->val != val) {
head = head->next;
}
return head;
}
#ifdef __cplusplus
}
#endif
#endif // LIST_NODE_H