.任意输入一组复数,将该组复数按模从小到大排列(用单链表实现)。 struct Complex { double real; double imag; };
时间: 2024-05-24 08:09:59 浏览: 5
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
struct Complex {
double real;
double imag;
};
struct Node {
struct Complex data;
struct Node* next;
};
void insert(struct Node** head, struct Complex data) {
struct Node* newNode = (struct Node*) malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
} else if (sqrt(newNode->data.real * newNode->data.real + newNode->data.imag * newNode->data.imag) < sqrt((*head)->data.real * (*head)->data.real + (*head)->data.imag * (*head)->data.imag)) {
newNode->next = *head;
*head = newNode;
} else {
struct Node* current = *head;
while (current->next != NULL && sqrt(newNode->data.real * newNode->data.real + newNode->data.imag * newNode->data.imag) >= sqrt(current->next->data.real * current->next->data.real + current->next->data.imag * current->next->data.imag)) {
current = current->next;
}
newNode->next = current->next;
current->next = newNode;
}
}
void printList(struct Node* head) {
while (head != NULL) {
printf("%.2f + %.2fi ", head->data.real, head->data.imag);
head = head->next;
}
printf("\n");
}
int main() {
int n;
printf("Enter the number of complex numbers: ");
scanf("%d", &n);
struct Node* head = NULL;
printf("Enter the complex numbers:\n");
for (int i = 0; i < n; i++) {
struct Complex c;
scanf("%lf %lf", &c.real, &c.imag);
insert(&head, c);
}
printf("The complex numbers sorted by modulus in ascending order are: ");
printList(head);
return 0;
}
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](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)