c - 如何对结构进行排序
问题描述
我在 C 中有如下结构:
typedef struct node {
int id;
int salary;
struct node *next;
char name[30];
char phone[10];
char position[30];
} List;
我还有两个变量 List 类型,我想按 id 对结构进行排序(最大的 id 将在最后)。我的想法如何解决这个问题:
- 在 *head 上执行 **pointer (*head = List 的第一个成员上的指针)。
- 检查 **pointer.id 是否大于 **pointer.next.id 如果是 -> **pointer.next 将指向 *pointer.next.next **pointer.next.next 将指向 &pointer
这是解决这个问题的代码(我将在之后对代码和冒泡排序算法进行“修饰”。Firstable 只是想构建可以工作的代码):
void sort(List head) {
int length = getListLength(head);
List **currentNode = &head;
for(int i = 0; i < length; i++) {
**currentNode = &head;
for(int j = 0; j < length; j++) {
if(currentNode->id > currentNode->next->id) {
currentNode->next = currentNode->next->next;
currentNode->next->next = ¤tNode;
}
}
}
}
有错误:
^ ~~~~~
list.c:92:19: error: assigning to 'List' (aka 'struct node') from incompatible type 'List *' (aka 'struct node *'); remove &
**currentNode = &head;
^ ~~~~~
list.c:94:21: error: member reference base type 'List *' (aka 'struct node *') is not a structure or union
if(currentNode->id > currentNode->next->id) {
~~~~~~~~~~~^ ~~
list.c:94:39: error: member reference base type 'List *' (aka 'struct node *') is not a structure or union
if(currentNode->id > currentNode->next->id) {
~~~~~~~~~~~^ ~~~~
list.c:95:20: error: member reference base type 'List *' (aka 'struct node *') is not a structure or union
currentNode->next = currentNode->next->next;
~~~~~~~~~~~^ ~~~~
list.c:95:40: error: member reference base type 'List *' (aka 'struct node *') is not a structure or union
currentNode->next = currentNode->next->next;
~~~~~~~~~~~^ ~~~~
list.c:96:20: error: member reference base type 'List *' (aka 'struct node *') is not a structure or union
currentNode->next->next = ¤tNode;
~~~~~~~~~~~^ ~~~~
请给我一些方法来解决这个问题(不解决问题。只想知道我的代码有什么问题,然后自己修复它)。
主功能:
int main() {
List *head = (List *) malloc(sizeof(List));
if(head == NULL) {
return 1;
}
head -> id = 332513075;
head -> salary = 1000;
strcpy(head -> name, "Name Lastname");
strcpy(head -> phone, "0587885238");
strcpy(head -> position, "cleaner");
head -> next = (List *) malloc(sizeof(List));
head -> next->id = 2;
head -> next->salary = 2000;
strcpy(head -> next -> name, "Another name");
strcpy(head -> next -> phone, "1234567890");
strcpy(head -> next -> position, "CEO");
head -> next -> next = NULL;
sort(*head);
print_list(*head);
return 0;
}
解决方案
第一个错误:
head
是 aList
,所以&head
是 aList*
; 但您正试图将其分配给List**
.其他的源于将
currentNode
其视为List*
.
所以声明currentNode
为 aList*
将解决列出的错误。
推荐阅读
- api - 我们什么时候应该在 uri 路径中使用冒号?
- javascript - Laravel + Inertia 中带有 API 调用的 Vue 组件
- javascript - 获取不包括 innerHTML 的元素的完整 HTML
- python - 有关解析/替换错误的更多信息
- go - 如何访问 map[string]interface {}?
- google-cloud-platform - 如何在谷歌云中打开“http://localhost:8081/”?
- java - 我想跳过预期 JSON 文件中的一些键,以便与 JSON 响应进行比较
- google-sheets - 具有挑战性的 importxml 任务
- python - 比使用带有 JSON 的 python 管理数据更快的方法
- python - Scipy odeint。引力运动