#include <stdio.h>
#include <stdlib.h>
#define MY_DEBUG 1
#if MY_DEBUG
#define myDebug(fmt, ...) printf("[fun:%s - line:%d] " fmt, __FUNCTION__, __LINE__, ##__VA_ARGS__)
#else
#define myDebug(fmt, ...)
#endif
// 定义节点结构体
typedef struct Node {
int data;
struct Node* next;
} Node;
// 创建一个新的节点
Node* createNode(int value)
{
myDebug("Node len=%d\n",sizeof(Node));
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = newNode; // 初始时指向自己,形成循环
return newNode;
}
// 在链表的尾部插入节点
void insert(Node** head, int value)
{
Node* newNode = createNode(value);
if (*head == NULL)//如果还没有给头申请内存空间
{
*head = newNode;
myDebug("p of head=%p\n",head);
}
else
{
Node* temp = *head;
myDebug("p of head=%p\n",*head);
myDebug("p of temp->next=%p\n",temp->next);
while (temp->next != *head)//遍历找到链表尾部
{
temp = temp->next;
myDebug("p of temp->next=%p\n",temp->next);
}
myDebug("p of temp=%p\n",temp);
temp->next = newNode;
myDebug("p of temp->next=%p\n",temp->next);
}
newNode->next = *head; // 形成循环
//myDebug("p of head=%p\n",head);
}
// 删除指定值的节点
void deleteNode(Node** head, int value) {
if (*head == NULL) return;
Node *temp = *head, *prev = NULL;
// 如果要删除的是头节点
if (temp->data == value)
{
if (temp->next == *head)
{
free(temp);
*head = NULL; // 只剩一个节点
return;
}
else
{
// 找到最后一个节点
while (temp->next != *head)
{
temp = temp->next;
}
temp->next = (*head)->next; // 更新最后一个节点的 next 指针
Node* toDelete = *head;
*head = (*head)->next; // 更新头节点
free(toDelete);
return;
}
}
// 寻找要删除的节点
while (temp->next != *head && temp->next->data != value)
{
temp = temp->next;
}
if (temp->next != *head)
{
Node* toDelete = temp->next;
temp->next = toDelete->next;
free(toDelete);
}
else
{
printf("Value %d not found.\n", value);
}
}
// 查找节点
Node* findNode(Node* head, int value)
{
if (head == NULL) return NULL;
Node* temp = head;
do
{
if (temp->data == value)
{
return temp;
}
temp = temp->next;
}
while (temp != head);
return NULL; // 没找到
}
// 更新节点值
void updateNode(Node* head, int oldValue, int newValue)
{
Node* node = findNode(head, oldValue);
if (node)
{
node->data = newValue;
}
else
{
printf("Value %d not found for update.\n", oldValue);
}
}
// 打印链表
void printList(Node* head)
{
if (head == NULL) return;
Node* temp = head;
do
{
printf("%d -> ", temp->data);
temp = temp->next;
}
while (temp != head);
printf("(back to head)\n");
}
// 释放链表
void freeList(Node* head) {
if (head == NULL) return;
Node* current = head;
Node* nextNode;
do {
nextNode = current->next;
free(current);
current = nextNode;
} while (current != head);
}
// 主函数
int main() {
Node* head = NULL;
// 插入节点
insert(&head, 10);
insert(&head, 20);
insert(&head, 30);
insert(&head, 40);
printList(head);
// 更新节点
updateNode(head, 20, 25);
printList(head);
// 查找节点
Node* found = findNode(head, 25);
if (found) {
printf("Found node with value: %d\n", found->data);
}
// 删除节点
deleteNode(&head, 10);
printList(head);
// 释放链表
freeList(head);
return 0;
}
11-25
2024
01-06
3462
09-26
09-26