怎样随机给出一个单链表
时间: 2024-05-04 20:15:17 浏览: 9
以下是随机生成一个单链表的 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)` 随机生成节点的值。
相关问题
用c++创建一个随机长度随机元素的单链表
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct node {
int data;
struct node *next;
} Node;
Node *createRandomList() {
srand(time(NULL)); //设置随机数发生器的种子
int len = rand() % 10 + 1; //生成1到10之间的随机数作为链表的长度
Node *head = NULL, *tail = NULL;
for (int i = 0; i < len; i++) {
Node *newNode = (Node *) malloc(sizeof(Node));
newNode->data = rand() % 100; //生成0到99之间的随机数作为节点的数据
newNode->next = NULL;
if (head == NULL) {
head = tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
return head;
}
void printList(Node *head) {
Node *p = head;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
Node *head = createRandomList();
printList(head);
return 0;
}
将随机生成数据后的单链表中的数据赋给一个数组
好的,针对您的问题,我可以提供以下的代码实现,假设链表的头节点为 `head`,链表中的元素类型为 `int`,数组的名称为 `arr`,数组的长度为 `len`:
```c++
int *arr = new int[len]; // 动态分配数组空间
int i = 0;
Node* cur = head;
while (cur != nullptr && i < len) {
arr[i++] = cur->val; // 将链表中的元素逐个存入数组
cur = cur->next;
}
```
上述代码中,我们首先通过 `new` 运算符动态分配了一个长度为 `len` 的数组空间,然后使用 `while` 循环遍历链表,将链表中的元素逐个存入数组中,最后得到了一个保存了链表元素的数组。需要注意的是,由于数组长度可能小于链表长度,所以在遍历链表时需要同时判断数组是否已经填满,以免数组越界。