在C语言中,链表是一种用于存储数据元素的非连续性内存分配的数据结构。链表的每个元素(称为节点)含有两部分组成:一个是储存数据的区域,另一个是指向链表下一个节点的指针。要实现链表操作,首先需要定义一个节点结构体,然后实现链表的各种操作函数,如插入、删除、查找和遍历等。
以下是一个简单的C语言链表操作实现:
#include <stdio.h>
#include <stdlib.h>
typedef int ElementType; // 数据类型,可以根据需要修改
typedef struct Node {
ElementType data; // 数据域
struct Node *next; // 指针域
} Node;
Node *createNode(ElementType data) {
Node *newNode = (Node *)malloc(sizeof(Node));
if (newNode == NULL) {
printf("Memory allocation failed.\n");
exit(1);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}
Node *insertNode(Node *head, ElementType data) {
Node *newNode = createNode(data);
if (head == NULL) {
head = newNode;
} else {
newNode->next = head;
head = newNode;
}
return head;
}
Node *deleteNode(Node *head, ElementType data) {
Node *temp = head;
Node *prev = NULL;
if (temp != NULL && temp->data == data) {
head = temp->next;
free(temp);
return head;
}
while (temp != NULL && temp->data != data) {
prev = temp;
temp = temp->next;
}
if (temp == NULL) {
printf("Node with data %d not found.\n", data);
return head;
}
prev->next = temp->next;
free(temp);
return head;
}
Node *findNode(Node *head, ElementType data) {
Node *temp = head;
while (temp != NULL) {
if (temp->data == data) {
return temp;
}
temp = temp->next;
}
return NULL; // 如果未找到,返回NULL
}
void traverseList(Node *head) {
Node *temp = head;
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
int main() {
Node *head = NULL;
head = insertNode(head, 5);
head = insertNode(head, 3);
head = insertNode(head, 8);
head = insertNode(head, 1);
printf("Original list: ");
traverseList(head);
head = deleteNode(head, 3);
printf("List after deleting 3: ");
traverseList(head);
Node *foundNode = findNode(head, 8);
if (foundNode != NULL) {
printf("Found node with data: %d\n", foundNode->data);
} else {
printf("Node not found.\n");
}
return 0;
}
这个例子展示了如何在C语言中实现一个简单的链表及其基本操作。你可以根据需要修改数据类型、操作函数等以满足实际需求。