定一个长度为N(不大于500)的正整数序列,请将其中的所有奇数取出,并按升序输出。利用链表使用c语言
时间: 2024-06-01 17:12:34 浏览: 21
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
void add(Node** head, int data) {
Node* new_node = (Node*)malloc(sizeof(Node));
new_node->data = data;
new_node->next = *head;
*head = new_node;
}
void print_list(Node* head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
int main() {
int n, i, x;
Node* head = NULL;
scanf("%d", &n);
for (i = 0; i < n; i++) {
scanf("%d", &x);
if (x % 2 == 1) {
add(&head, x);
}
}
print_list(head);
return 0;
}
相关问题
给定一个长度为N(不大于500)的正整数序列,请将其中的所有奇数取出,并按升序输出。c语言
以下是C语言的代码实现,可以将一个长度为N的正整数序列中的所有奇数取出,并按升序输出:
```c
#include <stdio.h>
int main()
{
int N;
scanf("%d", &N);
int arr[N], odd[N], j = 0;
for (int i = 0; i < N; i++) {
scanf("%d", &arr[i]);
if (arr[i] % 2 != 0) {
odd[j] = arr[i];
j++;
}
}
for (int i = 0; i < j - 1; i++) {
for (int k = 0; k < j - i - 1; k++) {
if (odd[k] > odd[k + 1]) {
int temp = odd[k];
odd[k] = odd[k + 1];
odd[k + 1] = temp;
}
}
}
for (int i = 0; i < j; i++) {
printf("%d ", odd[i]);
}
return 0;
}
```
给定一个长度为n(不大于500)的正整数序列,请将其中的所有奇数取出,并按升序输出。
好的,以下是将给定的长度为n的正整数序列中的所有奇数取出,并按升序输出的代码示例:
```python
# 获取输入的正整数序列
n = int(input())
arr = list(map(int, input().split()))
# 从序列中筛选出所有奇数
odds = [num for num in arr if num % 2 == 1]
# 对筛选出的奇数序列进行升序排序
odds.sort()
# 输出结果
for num in odds:
print(num, end=' ')
```
希望这可以帮助您解决问题!
相关推荐
![text/x-c](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)