c++实现泛型循环链表
时间: 2023-03-24 09:03:21 浏览: 148
可以使用 void 指针来实现泛型循环链表,具体实现方法可以参考以下代码:
```
typedef struct node {
void *data;
struct node *next;
} Node;
typedef struct {
Node *head;
Node *tail;
int size;
} List;
List *list_create() {
List *list = (List *)malloc(sizeof(List));
list->head = NULL;
list->tail = NULL;
list->size = ;
return list;
}
void list_add(List *list, void *data) {
Node *node = (Node *)malloc(sizeof(Node));
node->data = data;
node->next = NULL;
if (list->head == NULL) {
list->head = node;
list->tail = node;
node->next = node;
} else {
list->tail->next = node;
node->next = list->head;
list->tail = node;
}
list->size++;
}
void list_remove(List *list, void *data) {
Node *prev = list->tail;
Node *curr = list->head;
int i;
for (i = ; i < list->size; i++) {
if (curr->data == data) {
if (curr == list->head) {
list->head = curr->next;
list->tail->next = list->head;
} else if (curr == list->tail) {
list->tail = prev;
list->tail->next = list->head;
} else {
prev->next = curr->next;
}
free(curr);
list->size--;
return;
}
prev = curr;
curr = curr->next;
}
}
void list_destroy(List *list) {
Node *curr = list->head;
int i;
for (i = ; i < list->size; i++) {
Node *temp = curr;
curr = curr->next;
free(temp);
}
free(list);
}
```
以上代码实现了一个泛型循环链表,可以存储任意类型的数据。
阅读全文
相关推荐















