生成一个长度为10的单链表
时间: 2024-05-05 19:18:11 浏览: 7
可以使用以下Python代码生成长度为10的单链表:
```
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
head = ListNode()
curr = head
for i in range(1, 11):
curr.next = ListNode(i)
curr = curr.next
```
这段代码创建了一个链表头"head",然后依次循环生成值为1到10的节点,并将它们链接到链表中。最后返回头结点即可得到所求的长度为10的单链表。
相关问题
用c++生成一个长度为10的单链表
好的,我可以为您提供一个生成单链表的示例程序,请您参考如下代码:
```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 函数的正确性,并输出生成的单链表。
如有任何疑问,欢迎随时提出。
怎样随机给出一个单链表
以下是随机生成一个单链表的 Python 代码示例:
```python
import random
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def generate_linked_list(n):
if n == 0:
return None
head = ListNode(random.randint(1, 100))
curr = head
for i in range(1, n):
curr.next = ListNode(random.randint(1, 100))
curr = curr.next
return head
```
使用方法:
```python
head = generate_linked_list(5) # 随机生成长度为 5 的单链表
```
其中,`ListNode` 为链表节点的类,`generate_linked_list` 函数接受一个参数 `n`,表示链表的长度,返回生成的链表头节点。在生成链表时,使用 `random.randint(1, 100)` 随机生成节点的值。