2. 创建一个单链表,把 1-100 中的质数存放到一个单链表中去。
时间: 2024-04-29 17:22:31 浏览: 11
好的,这个问题我可以回答。下面是创建单链表存放 1-100 中的质数的代码:
```python
class Node:
def __init__(self, val):
self.val = val
self.next = None
def isPrime(n):
if n == 1:
return False
for i in range(2, int(n/2)+1):
if n%i == 0:
return False
return True
head = Node(-1)
cur = head
for i in range(1, 101):
if isPrime(i):
new_node = Node(i)
cur.next = new_node
cur = new_node
cur = head.next # 去掉头结点
while cur:
print(cur.val, end=' ')
cur = cur.next
```
这个程序会先判断 1-100 中每个数是否是质数,然后把质数存到一个单链表中去。最后,程序会输出这个单链表中的所有节点。
注:这里的代码只用于回答问题,可能还需要针对具体应用场景做出调整和优化。
相关问题
2.js 创建一个单链表,把 1-100 中的质数存放到一个单链表中去。
好的,这个问题是关于编程实现的,我可以为你提供代码示例。以下是使用 JavaScript 实现一个单链表,将 1-100 中的质数存储到该单链表中的示例代码:
```javascript
// 定义一个单链表节点
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
// 定义一个单链表类
class LinkedList {
constructor() {
this.head = null;
this.tail = null;
this.length = 0;
}
// 添加节点到链表末尾
append(value) {
const node = new Node(value);
if (!this.head) {
this.head = node;
this.tail = node;
} else {
this.tail.next = node;
this.tail = node;
}
this.length++;
}
}
// 判断是否为质数的函数
function isPrime(n) {
if (n <= 1) return false;
for (let i = 2; i <= Math.sqrt(n); i++) {
if (n % i === 0) return false;
}
return true;
}
// 创建单链表,在其中存储 1-100 中的质数
const linkedList = new LinkedList();
for (let i = 1; i <= 100; i++) {
if (isPrime(i)) {
linkedList.append(i);
}
}
```
运行上述代码后,我们就可以在 `linkedList` 中存储 1-100 中的质数了。
5. 创建一个单链表,判断这个链表中有哪些结点的值是素数和偶数。
好的,这是一道编程问题,不涉及任何敏感话题。以下是我的回答:
要判断链表中结点值的素数和偶数,需要遍历整个链表,并对每个结点的值进行判断。可以使用 while 循环遍历链表,对于每个结点,用 if 语句判断它是否为素数或偶数,如果是,则记录下这个结点的信息。最后输出所有符合条件的结点即可。
下面是用 Python 语言实现的代码:
``` python
class Node:
def __init__(self, val):
self.val = val
self.next = None
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5)+1):
if n % i == 0:
return False
return True
def is_even(n):
return n % 2 == 0
def find_nodes(head):
primes = []
evens = []
current = head
while current:
if is_prime(current.val):
primes.append(current)
if is_even(current.val):
evens.append(current)
current = current.next
return primes, evens
# Example usage:
# head = Node(1)
# head.next = Node(2)
# head.next.next = Node(3)
# primes, evens = find_nodes(head)
# for prime in primes:
# print(prime.val)
# for even in evens:
# print(even.val)
```
请注意,这只是一种实现方式,可能不是最优的,也可以用其他语言实现。希望这个回答能够帮到你。