How to create and use linked lists in the C programming language?
The steps to create a linked list are as follows:
- Define a struct to represent a node of a linked list, which includes a data field and a pointer to the next node.
- Create a pointer pointing to the head node of the linked list.
- Dynamically allocate memory to create a linked list node, and store data in the node’s data field.
- Insert the newly created node into the linked list.
The general steps for using a linked list are as follows:
- Start from the head node of the linked list and access each node in the list by following the pointers.
- Output or process the value of the data field of a node.
- Point the pointer to the next node and continue looping until reaching the end of the linked list, which is when the pointer is empty.
- Create a new node and allocate memory for it.
- Save the data into the data field of the new node.
- Adjust the pointers of the nodes in the linked list to insert the new node into the appropriate position.
- Find the node before the one you want to delete.
- Adjust the pointers of the nodes to skip the node to be deleted.
- Release the memory of the deleted node.
Here is a simple example code using a linked list implementation:
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct Node {
int data; // 数据域
struct Node *next; // 指向下一个节点的指针
} Node;
// 创建链表节点
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (newNode == NULL) {
printf("内存分配失败!\n");
exit(1);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// 插入节点到链表末尾
void insertNode(Node** head, int data) {
Node* newNode = createNode(data); // 创建新节点
if (*head == NULL) {
*head = newNode; // 若链表为空,则新节点为头节点
} else {
Node* current = *head;
while (current->next != NULL) {
current = current->next; // 遍历链表直到最后一个节点
}
current->next = newNode; // 将新节点插入到链表末尾
}
}
// 删除指定值的节点
void deleteNode(Node** head, int data) {
Node* current = *head;
Node* previous = NULL;
while (current != NULL) {
if (current->data == data) {
if (previous == NULL) {
*head = current->next; // 如果要删除的节点是头节点
} else {
previous->next = current->next; // 跳过当前节点
}
free(current); // 释放被删除节点的内存
return;
}
previous = current;
current = current->next;
}
printf("要删除的节点不存在!\n");
}
// 遍历链表并输出节点的值
void traverseList(Node* head) {
Node* current = head;
printf("链表节点的值:");
while (current != NULL) {
printf(" %d", current->data);
current = current->next;
}
printf("\n");
}
int main() {
Node* head = NULL; // 头节点指针初始化为空
insertNode(&head, 1);
insertNode(&head, 2);
insertNode(&head, 3);
insertNode(&head, 4);
insertNode(&head, 5);
traverseList(head); // 输出链表节点的值
deleteNode(&head, 3);
traverseList(head);
return 0;
}
The above is a basic example of linked list operations, including creating nodes, inserting nodes, deleting nodes, and traversing the list. It can be expanded and modified according to actual needs.