链表(Linked List)是一种常见的数据结构,它由一系列节点(Node)组成,每个节点包含数据部分和一个指向下一个节点的指针。链表可以分为单向链表、双向链表和循环链表等类型。
链表常用于实现队列、栈、图等数据结构,也常用于需要频繁插入和删除操作的场景。
在Linux环境下,删除链表节点通常涉及以下步骤:
以下是一个简单的C语言示例,展示如何删除单向链表中的一个节点:
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
struct Node {
int data;
struct Node* next;
};
// 删除链表中的节点
void deleteNode(struct Node** head_ref, int key) {
// 如果头节点就是要删除的节点
if (*head_ref != NULL && (*head_ref)->data == key) {
struct Node* temp = *head_ref;
*head_ref = (*head_ref)->next;
free(temp);
return;
}
// 查找要删除的节点
struct Node* current = *head_ref;
struct Node* previous = NULL;
while (current != NULL && current->data != key) {
previous = current;
current = current->next;
}
// 如果找到了要删除的节点
if (current != NULL) {
previous->next = current->next;
free(current);
}
}
// 打印链表
void printList(struct Node* node) {
while (node != NULL) {
printf("%d -> ", node->data);
node = node->next;
}
printf("NULL\n");
}
int main() {
struct Node* head = NULL;
// 创建链表 1 -> 2 -> 3 -> 4 -> 5
for (int i = 5; i > 0; i--) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = i;
newNode->next = head;
head = newNode;
}
printf("Original list: ");
printList(head);
int key = 3;
deleteNode(&head, key);
printf("List after deleting %d: ", key);
printList(head);
return 0;
}
free
函数释放节点内存。通过以上步骤和示例代码,可以有效地在Linux环境下删除链表中的节点。
领取专属 10元无门槛券
手把手带您无忧上云