酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

用c++写代码 1.实现单循环链表的初始化、求数据元素个数、插入、删除、取数据元素 等操作; 2.用插入法建立带头结点的单循环链表; 3.设计一个测试主函数验证所设计单循环链表的正确性。

#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点数解答]

相关提问