4fb7ee7edb
完成基本逻辑
99 lines
2.1 KiB
C
99 lines
2.1 KiB
C
// linkedlist.c
|
|
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include "linkedlist.h"
|
|
|
|
// 创建新节点并为其分配不定长数组
|
|
Node* createNode(int* arr, int size) {
|
|
Node* newNode = (Node*)malloc(sizeof(Node));
|
|
if (!newNode) {
|
|
printf("内存分配失败\n");
|
|
exit(1);
|
|
}
|
|
|
|
newNode->data = (int*)malloc(size * sizeof(int)); // 分配数组内存
|
|
if (!newNode->data) {
|
|
printf("数组内存分配失败\n");
|
|
free(newNode); // 释放节点内存
|
|
exit(1);
|
|
}
|
|
|
|
for (int i = 0; i < size; i++) {
|
|
newNode->data[i] = arr[i];
|
|
}
|
|
|
|
newNode->size = size;
|
|
newNode->next = NULL;
|
|
return newNode;
|
|
}
|
|
|
|
// 向链表末尾添加节点
|
|
void appendNode(Node** head, int* arr, int size) {
|
|
Node* newNode = createNode(arr, size);
|
|
|
|
if (*head == NULL) {
|
|
*head = newNode;
|
|
return;
|
|
}
|
|
|
|
Node* temp = *head;
|
|
while (temp->next != NULL) {
|
|
temp = temp->next;
|
|
}
|
|
|
|
temp->next = newNode;
|
|
}
|
|
|
|
// 删除链表的第一个节点
|
|
void deleteFirstNode(Node** head) {
|
|
if (*head == NULL) {
|
|
printf("链表为空,无法删除第一个节点。\n");
|
|
return;
|
|
}
|
|
|
|
Node* temp = *head;
|
|
*head = (*head)->next;
|
|
|
|
free(temp->data); // 释放数组
|
|
free(temp); // 释放节点
|
|
|
|
printf("第一个节点已删除。\n");
|
|
}
|
|
|
|
// 打印链表
|
|
void printList(Node* head) {
|
|
Node* temp = head;
|
|
while (temp != NULL) {
|
|
printf("节点数组: ");
|
|
for (int i = 0; i < temp->size; i++) {
|
|
printf("%d ", temp->data[i]);
|
|
}
|
|
printf("\n");
|
|
temp = temp->next;
|
|
}
|
|
}
|
|
|
|
// 释放链表占用的内存
|
|
void freeList(Node* head) {
|
|
Node* temp;
|
|
while (head != NULL) {
|
|
temp = head;
|
|
head = head->next;
|
|
free(temp->data); // 释放节点中的数组
|
|
free(temp); // 释放节点本身
|
|
}
|
|
}
|
|
|
|
// 获取链表中节点的数量
|
|
int getListSize(Node* head) {
|
|
int count = 0;
|
|
Node* temp = head;
|
|
|
|
while (temp != NULL) {
|
|
count++;
|
|
temp = temp->next;
|
|
}
|
|
|
|
return count;
|
|
} |