在C語言中,鏈表是一種用于存儲(chǔ)數(shù)據(jù)元素的非連續(xù)性內(nèi)存分配的數(shù)據(jù)結(jié)構(gòu)。鏈表的每個(gè)元素(稱為節(jié)點(diǎn))含有兩部分組成:一個(gè)是儲(chǔ)存數(shù)據(jù)的區(qū)域,另一個(gè)是指向鏈表下一個(gè)節(jié)點(diǎn)的指針。要實(shí)現(xiàn)鏈表操作,首先需要定義一個(gè)節(jié)點(diǎn)結(jié)構(gòu)體,然后實(shí)現(xiàn)鏈表的各種操作函數(shù),如插入、刪除、查找和遍歷等。
以下是一個(gè)簡(jiǎn)單的C語言鏈表操作實(shí)現(xiàn):
#include <stdio.h>
#include <stdlib.h>
typedef int ElementType; // 數(shù)據(jù)類型,可以根據(jù)需要修改
typedef struct Node {
ElementType data; // 數(shù)據(jù)域
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;
}
這個(gè)例子展示了如何在C語言中實(shí)現(xiàn)一個(gè)簡(jiǎn)單的鏈表及其基本操作。你可以根據(jù)需要修改數(shù)據(jù)類型、操作函數(shù)等以滿足實(shí)際需求。