C++实现单循环链表:初始化、插入、删除等操作及测试验证
#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; } ######[AI写代码神器 | 2102点数解答 | 2024-10-13 13:39:58]
- C 语言实现单链表全功能操作:创建、增删查改与逆置测试( | 4796点数解答 | 2024-03-28 16:24:20)342
- C++实现顺序存储结构基本操作:初始化、插入、删除等全解析(GPT | 1743点数解答 | 2024-09-26 00:20:17)283
- Python实现Q老师成绩管理任务:修改与查看学生成绩(字节豆包 | 191点数解答 | 2025-12-20 20:55:41)70
- Python 代码助力 Q 老师高效管理班级学生成绩:修改与查看一键搞定(字节豆包 | 326点数解答 | 2025-12-27 20:48:12)73
- Linux 系统用户、组及文件操作全流程实践(字节豆包 | 1142点数解答 | 2026-03-20 17:29:38)11
- Python 实现球类:精准计算半径、表面积与体积,附输入验证与异常处理!(阿里通义 | 261点数解答 | 2024-11-28 21:19:39)345
- C++实现单循环链表:初始化、插入、删除等操作及测试验证(GPT | 2102点数解答 | 2024-10-13 13:39:58)157
- Java 实现通用文件存储系统:含随机读写与空闲空间回收(字节豆包 | 686点数解答 | 2024-11-21 16:25:51)225
- C#工程师必知:数组、链表、哈希、队列、栈数据结构优缺点大揭秘! (百度文心 | 561点数解答 | 2023-11-09 17:56:30)263
- Java 实现仿 Windows 资源管理器:文件管理器功能全解析与代码示例(字节豆包 | 623点数解答 | 2025-01-01 14:59:04)248
- 51 单片机:定时器 0 实现 8 个 LED 循环点亮,附代码及优化建议(字节豆包 | 1193点数解答 | 2024-12-27 15:10:29)313
- C++实现最短编辑距离计算:将一个单词转换为另一个的最少操作数揭秘(字节豆包 | 311点数解答 | 2025-11-12 14:55:49)54