#include <iostream> using namespace std; // 定义节点结构体 struct Node { int data; Node* next; }; class CircularLinkedList { private: Node* head; public: // 初始化链表 CircularLinkedList() { head = nullptr; } // 求数据元素个数 int getSize() { if (head == nullptr) { return 0; } Node* current = head; int size = 1; while (current->next != head) { size++; current = current->next; } return size; } // 插入数据元素 void insert(int newData) { Node* newNode = new Node; newNode->data = newData; if (head == nullptr) { head = newNode; head->next = head; } else { Node* current = head; while (current->next != head) { current = current->next; } current->next = newNode; newNode->next = head; } } // 删除数据元素 void remove(int targetData) { if (head == nullptr) { cout << "List is empty" << endl; return; } Node* current = head; Node* prev = nullptr; do { if (current->data == targetData) { if (current == head) { Node* temp = head; while (temp->next != head) { temp = temp->next; } temp->next = head->next; head = head->next; delete current; return; } else { prev->next = current->next; delete current; return; } } prev = current; current = current->next; } while (current != head); cout << "Data not found" << endl; } // 取出数据元素 int get(int index) { if (head == nullptr) { cout << "List is empty" << endl; return -1; } Node* current = head; int count = 0; while (count < index) { current = current->next; count++; } return current->data; } // 打印链表 void printList() { if (head == nullptr) { cout << "List is empty" << endl; return; } cout << "Circular Linked List: "; Node* current = head; do { cout << current->data << " "; current = current->next; } while (current != head); cout << endl; } }; int main() { CircularLinkedList list; // 插入元素 list.insert(1); list.insert(2); list.insert(3); list.insert(4); list.insert(5); // 打印链表 list.printList(); // 求元素个数 cout << "Size of the list: " << list.getSize() << endl; // 取出元素 cout << "Element at index 2: " << list.get(2) << endl; // 删除元素 list.remove(3); // 打印链表 list.printList(); return 0; } [2024-10-13 13:39:58 | AI写代码神器 | 2102点数解答]