c++建立长度为n的链表
时间: 2024-03-22 11:19:30 浏览: 14
下面是一个简单的示例,展示如何使用 C++ 建立长度为 n 的链表:
```c++
#include <iostream>
using namespace std;
// 定义链表节点结构体
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
// 建立长度为 n 的链表
ListNode* buildList(int n) {
if (n == 0) return NULL;
ListNode* head = new ListNode(0);
ListNode* cur = head;
for (int i = 1; i <= n; i++) {
ListNode* node = new ListNode(i);
cur->next = node;
cur = cur->next;
}
return head->next;
}
// 打印链表
void printList(ListNode* head) {
ListNode* cur = head;
while (cur) {
cout << cur->val << " ";
cur = cur->next;
}
cout << endl;
}
int main() {
ListNode* head = buildList(5);
printList(head);
return 0;
}
```
在上面的示例中,我们首先定义了一个 `ListNode` 结构体,用来表示链表节点,包含一个值域 `val` 和一个指向下一个节点的指针 `next`。
然后,我们定义了一个函数 `buildList`,用来建立长度为 n 的链表。在函数中,我们首先创建一个头节点 `head`,然后循环 n 次,创建 n 个节点,并将它们按顺序链接在一起。最后返回头节点的下一个节点,即整个链表的头节点。
最后,我们定义了一个函数 `printList`,用来打印链表。在函数中,我们从头节点开始遍历整个链表,依次输出每个节点的值域。
在 `main` 函数中,我们调用 `buildList` 函数建立了一个长度为 5 的链表,然后调用 `printList` 函数打印了这个链表。