首页 > 解决方案 > 如何对结构进行排序

问题描述

我在 C 中有如下结构:

typedef struct node {
  int id;
  int salary;
  struct node *next;
  char name[30];
  char phone[10];
  char position[30];
} List;

我还有两个变量 List 类型,我想按 id 对结构进行排序(最大的 id 将在最后)。我的想法如何解决这个问题:

  1. 在 *head 上执行 **pointer (*head = List 的第一个成员上的指针)。
  2. 检查 **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 = &currentNode;
      }
    }
  }
}

有错误:

         ^             ~~~~~
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 = &currentNode;
        ~~~~~~~~~~~^ ~~~~

请给我一些方法来解决这个问题(不解决问题。只想知道我的代码有什么问题,然后自己修复它)。

主功能:

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;
}

标签: csortingpointersstruct

解决方案


  • 第一个错误:head是 a List,所以&head是 a List*; 但您正试图将其分配给List**.

  • 其他的源于将currentNode其视为List*.

所以声明currentNode为 aList*将解决列出的错误。


推荐阅读