用c++生成一个长度为10的单链表
时间: 2024-05-11 18:15:56 浏览: 6
好的,我可以为您提供一个生成单链表的示例程序,请您参考如下代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* createList(int* nums, int numsSize) {
struct ListNode *head = NULL;
struct ListNode *tail = NULL;
for (int i = 0; i < numsSize; i++) {
struct ListNode *node = malloc(sizeof(struct ListNode));
node->val = nums[i];
node->next = NULL;
if (tail == NULL) {
head = tail = node;
} else {
tail->next = node;
tail = node;
}
}
return head;
}
int main() {
int nums[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int numsSize = sizeof(nums) / sizeof(nums[0]);
struct ListNode *head = createList(nums, numsSize);
printf("生成的单链表为:");
while (head != NULL) {
printf("%d ", head->val);
head = head->next;
}
printf("\n");
return 0;
}
```
以上程序使用了结构体 ListNode 来表示单链表结点,其中 val 表示结点的值,next 表示指向下一个结点的指针。createList 函数接受一个整型数组和数组大小作为参数,返回一个指向单链表头结点的指针。main 函数用于测试 createList 函数的正确性,并输出生成的单链表。
如有任何疑问,欢迎随时提出。