Đi qua các cấu trúc dữ liệu cổ điển và đã dừng lại trên danh sách được liên kết. Chỉ cần triển khai danh sách liên kết đơn lẻ tròn, nhưng tôi bị ấn tượng quá mức rằng danh sách này có thể được thể hiện một cách thanh lịch hơn, đặc biệt là chức năng remove_node. Lưu ý hiệu quả và khả năng đọc mã, có ai có thể trình bày giải pháp ngắn gọn và hiệu quả hơn cho danh sách vòng tròn đơn lẻ không?Thực hiện thanh lịch danh sách liên kết đơn lẻ trong C?
#include <stdio.h>
#include <stdlib.h>
struct node{
struct node* next;
int value;
};
struct list{
struct node* head;
};
struct node* init_node(int value){
struct node* pnode;
if (!(pnode = (struct node*)malloc(sizeof(struct node)))){
return NULL;
}
else{
pnode->value = value;
}
return pnode;
}
struct list* init_list(){
struct list* plist;
if (!(plist = (struct list*)malloc(sizeof(struct list)))){
return NULL;
}
plist->head = NULL;
return plist;
}
void remove_node(struct list*a plist, int value){
struct node* current, *temp;
current = plist->head;
if (!(current)) return;
if (current->value == value){
if (current==current->next){
plist->head = NULL;
free(current);
}
else {
temp = current;
do {
current = current->next;
} while (current->next != plist->head);
current->next = plist->head->next;
plist->head = current->next;
free(temp);
}
}
else {
do {
if (current->next->value == value){
temp = current->next;
current->next = current->next->next;
free(temp);
}
current = current->next;
} while (current != plist->head);
}
}
void print_node(struct node* pnode){
printf("%d %p %p\n", pnode->value, pnode, pnode->next);
}
void print_list(struct list* plist){
struct node * current = plist->head;
if (!(current)) return;
if (current == plist->head->next){
print_node(current);
}
else{
do {
print_node(current);
current = current->next;
} while (current != plist->head);
}
}
void add_node(struct node* pnode,struct list* plist){
struct node* current;
struct node* temp;
if (plist->head == NULL){
plist->head = pnode;
plist->head->next = pnode;
}
else {
current = plist->head;
if (current == plist->head->next){
plist->head->next = pnode;
pnode->next = plist->head;
}
else {
while(current->next!=plist->head)
current = current->next;
current->next = pnode;
pnode->next = plist->head;
}
}
}
Các sys di động và phổ biến/queue.h cung cấp một giao diện tương tự nhưng với sự linh hoạt hơn vì nó có đuôi hàng đợi, danh sách đơn lẻ liên kết, gấp đôi các danh sách liên kết và danh sách vòng tròn. Nó biên dịch thành mã rất nhỏ gọn mà không phải trả phí qua các cơ chế macro offset tương tự. –