设计循环单链表。循环单链表的操作,包括初始化,求元素个数,插入、删除元素、取元素,再设计一个测试主函数验证所设计循环单链表的正确性用c语言
时间: 2023-05-11 22:06:38 浏览: 107
以下是设计循环单链表的代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
typedef struct List {
Node* head;
int size;
} List;
void initList(List* list) {
list->head = NULL;
list->size = 0;
}
int getSize(List* list) {
return list->size;
}
void insert(List* list, int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
if (list->head == NULL) {
list->head = newNode;
newNode->next = list->head;
} else {
Node* current = list->head;
while (current->next != list->head) {
current = current->next;
}
current->next = newNode;
newNode->next = list->head;
}
list->size++;
}
void delete(List* list, int data) {
if (list->head == NULL) {
return;
}
Node* current = list->head;
Node* prev = NULL;
while (current->data != data) {
if (current->next == list->head) {
return;
}
prev = current;
current = current->next;
}
if (current == list->head && current->next == list->head) {
list->head = NULL;
} else if (current == list->head) {
Node* last = list->head;
while (last->next != list->head) {
last = last->next;
}
list->head = current->next;
last->next = list->head;
} else if (current->next == list->head) {
prev->next = list->head;
} else {
prev->next = current->next;
}
free(current);
list->size--;
}
int get(List* list, int index) {
if (index < 0 || index >= list->size) {
return -1;
}
Node* current = list->head;
for (int i = 0; i < index; i++) {
current = current->next;
}
return current->data;
}
void printList(List* list) {
if (list->head == NULL) {
printf("List is empty\n");
return;
}
Node* current = list->head;
do {
printf("%d ", current->data);
current = current->next;
} while (current != list->head);
printf("\n");
}
int main() {
List list;
initList(&list);
insert(&list, 1);
insert(&list, 2);
insert(&list, 3);
insert(&list, 4);
insert(&list, 5);
printf("List size: %d\n", getSize(&list));
printList(&list);
delete(&list, 3);
printf("List size: %d\n", getSize(&list));
printList(&list);
printf("Element at index 2: %d\n", get(&list, 2));
return 0;
}
```
以上代码实现了循环单链表的初始化、求元素个数、插入、删除元素、取元素等操作,并且包含了一个测试主函数,可以验证所设计循环单链表的正确性。
阅读全文