创建包含n个节点的单向链表
时间: 2023-09-20 15:04:37 浏览: 41
好的,以下是创建包含n个节点的单向链表的示例代码(使用C++语言实现):
```c++
#include <iostream>
using namespace std;
// 定义链表节点结构体
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
// 创建包含n个节点的单向链表
ListNode* createLinkedList(int n) {
ListNode *head = new ListNode(1); // 创建头节点
ListNode *tail = head; // 将尾指针指向头节点
for(int i = 2; i <= n; i++) {
ListNode *newNode = new ListNode(i); // 创建新节点
tail->next = newNode; // 将新节点添加至链表末尾
tail = newNode; // 更新尾指针
}
return head; // 返回头节点
}
int main() {
int n = 5;
ListNode *head = createLinkedList(n);
ListNode *p = head;
while(p != NULL) {
cout << p->val << " ";
p = p->next;
}
return 0;
}
```
这段代码会创建包含5个节点的单向链表,并将其打印输出。你可以根据需要更改n的值来创建不同节点数目的链表。