单向链表(Singly Linked List)是一种线性数据结构,其中每个元素(称为节点)包含一个数据域和一个指针域。这个指针域指向链表中的下一个节点。链表的第一个节点称为头节点(head),最后一个节点的指针域指向空(NULL),表示链表的结束。
以下是一个简单的单链表实现,包括节点定义和基本操作(插入、删除、遍历):
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构
struct Node {
int data;
struct Node* next;
};
// 创建新节点
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// 在链表头部插入节点
void insertAtHead(struct Node** head, int data) {
struct Node* newNode = createNode(data);
newNode->next = *head;
*head = newNode;
}
// 删除链表中的节点(假设节点存在)
void deleteNode(struct Node** head, int key) {
struct Node* temp = *head;
struct Node* prev = NULL;
if (temp != NULL && temp->data == key) {
*head = temp->next;
free(temp);
return;
}
while (temp != NULL && temp->data != key) {
prev = temp;
temp = temp->next;
}
if (temp == NULL) return;
prev->next = temp->next;
free(temp);
}
// 遍历并打印链表
void printList(struct Node* node) {
while (node != NULL) {
printf("%d -> ", node->data);
node = node->next;
}
printf("NULL\n");
}
int main() {
struct Node* head = NULL;
insertAtHead(&head, 3);
insertAtHead(&head, 2);
insertAtHead(&head, 1);
printf("Linked List:\n");
printList(head);
deleteNode(&head, 2);
printf("After deleting 2:\n");
printList(head);
return 0;
}
next
指针之前,确保节点不为空。next
指针之前,确保节点不为空。通过以上内容,你应该对Linux下的单向链表有了全面的了解,包括其基础概念、优势、类型、应用场景以及常见问题的解决方法。
腾讯云数据库TDSQL训练营
腾讯云数据库TDSQL(PostgreSQL版)训练营
2022OpenCloudOS社区开放日
云+社区沙龙online第6期[开源之道]
云原生正发声
腾讯云数据库TDSQL训练营
腾讯云数据库TDSQL训练营
腾讯云数据库TDSQL训练营
腾讯云数据库TDSQL训练营
腾讯云数据库TDSQL训练营
腾讯云数据库TDSQL训练营
领取专属 10元无门槛券
手把手带您无忧上云