创建一个由六个节点的单向链表
时间: 2023-11-13 11:05:21 浏览: 31
好的,我来帮您解决问题。以下是创建一个由六个节点的单向链表的C++代码示例:
```c++
#include <iostream>
using namespace std;
// 链表节点结构体
struct Node {
int data;
Node *next;
};
// 创建链表函数
Node* createLinkedList(int n) {
Node *head = NULL, *tail = NULL;
for (int i = 1; i <= n; ++i) {
Node *node = new Node();
node->data = i;
node->next = NULL;
if (head == NULL) {
head = tail = node;
} else {
tail->next = node;
tail = tail->next;
}
}
return head;
}
// 打印链表函数
void printLinkedList(Node *head) {
while (head != NULL) {
cout << head->data << " ";
head = head->next;
}
cout << endl;
}
int main() {
Node *head = createLinkedList(6);
printLinkedList(head);
return 0;
}
```
希望能够帮到您!