构建一个长度为n的循环链表(不含无意义的表头节点)使用C++
时间: 2023-12-03 20:44:00 浏览: 33
以下是使用C++实现长度为n的循环链表的代码:
```cpp
#include <iostream>
using namespace std;
// 定义循环链表节点结构体
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
// 构造循环链表
ListNode* createCircularLinkedList(int n) {
if (n <= 0) return NULL;
ListNode* head = new ListNode(1);
ListNode* cur = head;
for (int i = 2; i <= n; ++i) {
ListNode* node = new ListNode(i);
cur->next = node;
cur = node;
}
cur->next = head; // 将链表首尾相接,形成循环链表
return head;
}
// 打印循环链表
void printCircularLinkedList(ListNode* head) {
if (!head) return;
ListNode* cur = head;
cout << cur->val << " ";
cur = cur->next;
while (cur != head) {
cout << cur->val << " ";
cur = cur->next;
}
cout << endl;
}
int main() {
int n = 5;
ListNode* head = createCircularLinkedList(n);
printCircularLinkedList(head);
return 0;
}
```
运行结果:
```
1 2 3 4 5
```