C_DS_AIgo/linked_list.c

116 lines
1.7 KiB
C
Raw Permalink Normal View History

2025-03-17 16:27:15 +08:00
#include <stdio.h>
#include <stdlib.h>
#include "linked_list.h"
// <20><>ʼ<EFBFBD><CABC>ֵ
node* init_node(elem_type value)
2025-03-17 16:27:15 +08:00
{
node* new_node = (node*)malloc(sizeof(node));
2025-03-24 21:08:31 +08:00
if (new_node == NULL)
{
printf("error: malloc failed\n");
return NULL;
}
new_node->value = value;
2025-03-17 16:27:15 +08:00
new_node->next = NULL;
return new_node;
}
// ɾ<><C9BE><EFBFBD><EFBFBD>һ<EFBFBD><D2BB><EFBFBD>ڵ<EFBFBD>
void delete_node(node* n)
{
if (n->next != NULL) {
node* temp = n->next;
n->next = n->next->next;
free(temp);
}
2025-03-17 16:27:15 +08:00
}
// <20><EFBFBD>ڵ<EFBFBD>ֵ
void replace_node(node* n, elem_type value)
2025-03-17 16:27:15 +08:00
{
n->value = value;
2025-03-17 16:27:15 +08:00
}
2025-03-17 17:08:26 +08:00
// <20><><EFBFBD><EFBFBD><EFBFBD>ڵ<EFBFBD>
void insert_node(node* head,node *new_node)
2025-03-17 17:08:26 +08:00
{
new_node->next = head->next;
2025-03-17 17:08:26 +08:00
head->next = new_node;
}
// <20><><EFBFBD>ʽڵ<CABD>
int get_node(node* n)
{
return n->value;
}
// <20><><EFBFBD><EFBFBD>
address_node *find_node(node* head, elem_type value)
2025-03-17 17:08:26 +08:00
{
address_node* n = (address_node*)malloc(sizeof(address_node));
if (n == NULL) {
printf("<EFBFBD>ڴ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʧ<EFBFBD><EFBFBD>\n");
return NULL;
}
n->n = 1;
n->p = head->next;
node *temp = head;
while (temp->next != NULL)
2025-03-17 17:08:26 +08:00
{
if (temp->value == value)
2025-03-17 17:08:26 +08:00
return n;
n->n += 1;
temp = temp->next;
n->p = temp;
2025-03-17 17:08:26 +08:00
}
printf("<EFBFBD>޷<EFBFBD><EFBFBD>ҵ<EFBFBD><EFBFBD>ڵ<EFBFBD>\n");
free(n);
return NULL;
2025-03-17 17:08:26 +08:00
}
// <20><>ӡ<EFBFBD><D3A1><EFBFBD><EFBFBD>
void print_node_list(node* head)
{
node* head_1 = head;
//printf("[%d ",head_1->value);
printf("[");
while (1)
{
printf("%d ", head_1->value);
head_1 = head_1->next;
if (head_1 == NULL)
break;
}
printf("]\n");
2025-03-27 09:08:11 +08:00
}
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
int get_node_list(node* head)
{
node *head_1 = head;
int i = 1;
while (head_1->next != NULL)
2025-03-27 09:08:11 +08:00
{
head_1 = head_1->next;
2025-03-27 09:08:11 +08:00
i++;
}
printf("<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ϊ%d\n", i);
return i;
}
// <20><><EFBFBD><EFBFBD>Ԫ<EFBFBD><D4AA>
elem_type get_node_value(node* head,int pos)
2025-03-27 09:08:11 +08:00
{
node* head_1 = head;
2025-03-27 09:08:11 +08:00
int i = 1;
while (i < pos && head_1)
2025-03-27 09:08:11 +08:00
{
head_1 = head_1->next;
2025-03-27 09:08:11 +08:00
i++;
}
if (head_1 == NULL || i != pos)
return;
return head_1->value;
2025-03-17 17:08:26 +08:00
}