实现带表头结点的单链表 分文件布局代码; 实现单链表的初始化空链表、分别通过前插法/后插法创建链表、打印、求长度、查找、插入、删除、释放等操作;并在main函数中进行测试;
时间: 2024-10-23 22:15:55 浏览: 27
实现带表头节点的单链表,首先你需要定义一个结构体来表示链表的节点,包含数据域和指向下一个节点的指针。这里是一个简单的例子:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct Node {
int data; // 数据域
struct Node* next; // 指向下一个节点的指针
} Node;
// 初始化一个空链表
Node* createEmptyList() {
return (Node*)malloc(sizeof(Node)); // 分配内存
}
// 前插法创建链表(给定节点和值)
void prependToList(Node** head, int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = *head;
*head = newNode;
}
// 后插法创建链表(在尾部添加节点)
void appendToList(Node** head, int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
if (*head == NULL) { // 如果链表为空
*head = newNode;
return;
}
Node* last = *head;
while (last->next != NULL) { // 找到最后一个元素
last = last->next;
}
last->next = newNode;
}
// 打印链表
void printList(Node* head) {
Node* temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
// 计算链表长度
int listLength(Node* head) {
int length = 0;
while (head != NULL) {
length++;
head = head->next;
}
return length;
}
// 查找链表中的特定值
Node* findElement(Node* head, int value) {
Node* current = head;
while (current != NULL && current->data != value) {
current = current->next;
}
return current;
}
// 插入新元素(在指定位置插入)
void insertElement(Node** head, int value, int position) {
if (position <= 0) {
printf("Invalid position.\n");
return;
}
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = NULL;
if (position == 1) { // 插入在头部
newNode->next = *head;
*head = newNode;
} else {
Node* previous = head;
for (int i = 1; i < position - 1 && previous != NULL; ++i) {
previous = previous->next;
}
if (previous != NULL) {
newNode->next = previous->next;
previous->next = newNode;
}
}
}
// 删除链表中的元素(根据值或位置)
void deleteElement(Node** head, int value) {
if (*head == NULL) {
return;
}
if ((*head)->data == value) {
Node* temp = *head;
*head = (*head)->next;
free(temp);
} else {
Node* current = *head, *prev = NULL;
while (current != NULL && current->data != value) {
prev = current;
current = current->next;
}
if (current != NULL) {
prev->next = current->next;
free(current);
}
}
}
// 释放链表内存
void releaseList(Node** head) {
Node* temp;
while (*head != NULL) {
temp = *head;
*head = (*head)->next;
free(temp);
}
}
int main() {
Node* head = createEmptyList();
// 使用前插法创建链表
prependToList(&head, 5);
prependToList(&head, 3);
prependToList(&head, 1);
// 使用后插法创建链表
appendToList(&head, 8);
appendToList(&head, 6);
// 打印链表
printList(head);
printf("链表长度: %d\n", listLength(head));
// 查找元素
Node* foundNode = findElement(head, 5);
if (foundNode != NULL) {
printf("找到元素: %d\n", foundNode->data);
} else {
printf("未找到元素.\n");
}
// 插入和删除元素
insertElement(&head, 7, 3); // 插入元素7在位置3
deleteElement(&head, 3); // 删除值为3的元素
// 再次打印链表
printList(head);
// 释放内存
releaseList(&head);
return 0;
}
```
阅读全文