- 打卡等级:以坛为家I
- 打卡总天数:233
- 最近打卡:2025-04-30 16:08:37
金牌会员
- 积分
- 1490
|
发表于 2024-8-7 16:02:01
|
显示全部楼层
#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));
if (newNode == NULL) {
printf("内存分配失败!\n");
exit(1);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// 打印链表
void printList(struct Node* head) {
struct Node* current = head;
while (current!= NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
// 插入节点到链表头部
void insertAtHead(struct Node** head_ref, int new_data) {
struct Node* newNode = createNode(new_data);
newNode->next = (*head_ref);
(*head_ref) = newNode;
}
// 插入节点到链表尾部
void insertAtTail(struct Node** head_ref, int new_data) {
struct Node* newNode = createNode(new_data);
struct Node* last = *head_ref;
while (last->next!= NULL) {
last = last->next;
}
last->next = newNode;
newNode->next = NULL;
}
// 插入节点到指定位置
void insertAtPosition(struct Node** head_ref, int new_data, int position) {
struct Node* newNode = createNode(new_data);
struct Node* current = *head_ref;
struct Node* prev = NULL;
int i = 1;
while (i < position - 1 && current!= NULL) {
prev = current;
current = current->next;
i++;
}
if (current == NULL) {
printf("指定位置超出链表范围!\n");
return;
}
newNode->next = current;
prev->next = newNode;
}
// 删除链表节点
void deleteNode(struct Node* node) {
if (node == NULL) {
printf("要删除的节点为空!\n");
return;
}
struct Node* temp = node->next;
free(node);
node = temp;
}
// 释放链表内存
void freeList(struct Node* head) {
while (head!= NULL) {
struct Node* temp = head;
head = head->next;
free(temp);
}
}
int main() {
// 创建链表
struct Node* head = NULL;
// 插入节点到链表头部
insertAtHead(&head, 7);
insertAtHead(&head, 13);
insertAtHead(&head, 18);
// 打印链表
printf("创建链表后:\n");
printList(head);
// 插入节点到链表尾部
insertAtTail(&head, 56);
insertAtTail(&head, 31);
// 打印链表
printf("插入节点到链表尾部后:\n");
printList(head);
// 插入节点到指定位置
insertAtPosition(&head, 22, 3);
// 打印链表
printf("插入节点到指定位置后:\n");
printList(head);
// 删除链表节点
deleteNode(head->next->next);
// 打印链表
printf("删除链表节点后:\n");
printList(head);
// 释放链表内存
freeList(head);
return 0;
} |
|