在VS2022中创建一个结点数为i(用户输入)的链表,要求利用循环结构,创建链表单独定义一个函数
时间: 2023-08-04 17:35:00 浏览: 40
好的,我可以为你解答这个问题。
首先,我们需要定义链表节点的结构体:
```c++
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
```
接着,我们可以编写一个函数来创建一个指定长度的链表:
```c++
ListNode* createLinkedList(int n) {
ListNode* head = NULL;
ListNode* cur = NULL;
for (int i = 1; i <= n; i++) {
ListNode* node = new ListNode(i);
if (head == NULL) {
head = node;
cur = node;
} else {
cur->next = node;
cur = node;
}
}
return head;
}
```
在这个函数中,我们首先定义了一个链表头节点的指针 `head` 和一个当前节点的指针 `cur`,然后使用循环结构来创建链表节点,并将它们连接起来。
最后,我们返回链表头节点的指针,即可得到一个长度为 `n` 的链表。
完整代码如下:
```c++
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* createLinkedList(int n) {
ListNode* head = NULL;
ListNode* cur = NULL;
for (int i = 1; i <= n; i++) {
ListNode* node = new ListNode(i);
if (head == NULL) {
head = node;
cur = node;
} else {
cur->next = node;
cur = node;
}
}
return head;
}
int main() {
int n;
cout << "请输入链表的长度:";
cin >> n;
ListNode* head = createLinkedList(n);
cout << "链表的值为:";
while (head != NULL) {
cout << head->val << " ";
head = head->next;
}
cout << endl;
return 0;
}
```
希望能帮到你!