How to write a simple singly linked list in C language?
Here is a simple implementation of a singly linked list in C language.
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int val;
struct ListNode* next;
};
// 创建链表节点
struct ListNode* createNode(int value) {
struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
newNode->val = value;
newNode->next = NULL;
return newNode;
}
// 插入节点到链表尾部
void insert(struct ListNode** head, int value) {
struct ListNode* newNode = createNode(value);
if (*head == NULL) {
*head = newNode;
} else {
struct ListNode* cur = *head;
while (cur->next != NULL) {
cur = cur->next;
}
cur->next = newNode;
}
}
// 删除指定值的节点
void removeNode(struct ListNode** head, int value) {
struct ListNode* cur = *head;
struct ListNode* prev = NULL;
while (cur != NULL) {
if (cur->val == value) {
if (prev == NULL) { // 删除头节点
*head = cur->next;
} else {
prev->next = cur->next;
}
free(cur);
return;
}
prev = cur;
cur = cur->next;
}
}
// 打印链表
void printList(struct ListNode* head) {
struct ListNode* cur = head;
while (cur != NULL) {
printf("%d ", cur->val);
cur = cur->next;
}
printf("\n");
}
int main() {
struct ListNode* head = NULL;
// 插入节点
insert(&head, 1);
insert(&head, 2);
insert(&head, 3);
// 打印链表
printList(head);
// 删除节点
removeNode(&head, 2);
// 打印链表
printList(head);
return 0;
}
This code implements a simple singly linked list, which includes functions for creating nodes, inserting nodes, deleting nodes, and printing the list. The main() function demonstrates how to use these functions.