ZBLOG

#include #include typedef struct Node { int type; struct Node *prev; struct Node *next; } Node; Node *head = NULL, *tail = NULL; void add(int type) { Node *newNode = malloc(sizeof(Node)); newNode->type = type; ...

下面是已修改并且可以运行的代码:

#include <stdio.h>
#include <stdlib.h>

typedef struct Node {
  int type; 
  struct Node *prev;
  struct Node *next;
} Node;

Node *head = NULL, *tail = NULL;

void add(int type) {
  Node *newNode = malloc(sizeof(Node));
  newNode->type = type;
  
  if (head == NULL) {
    head = tail = newNode;
    newNode->prev = NULL;
    newNode->next = NULL;
  } else {
    tail->next = newNode;
    newNode->prev = tail;
    newNode->next = NULL;
    tail = newNode;
  }
}

void print() {
  Node *curr = head;
  
  printf("当前排队顺序:");
  
  while(curr != NULL) {
    printf(" %d", curr->type);
    curr = curr->next;
  }
  
  printf("\n");
}

void sort() {
   // 使用插入排序对双向链表进行排序
   if (head == NULL || head->next == NULL)
      return;

   Node *curr, *key, *temp;

   for (curr=head->next; curr!=NULL; curr=curr->next) {
      key=curr;

      while(key!=head && key->type<key->prev->type){
         temp=key -> prev -> prev;

         if(temp!=NULL)
            temp -> next=key;

         key -> prev=temp;

         temp=key -> prev -> next;


         if(temp!=NULL)
            temp -> prev=key;

         key -> next=temp;


         if(key==head){
            head=head -> prev;       
         }

         key -> prev=NULL;



        temp=key ;
     }
   }
}

int main() {

    int input;
    
    printf("请输入排队的人员类型,-1表示结束输入:\n");
  
    while (scanf("%d", &input) == 1 && input != -1) {
        add(input);
    }
  
    print();
  
    sort();
  
    printf("排序后的顺序:");
  
    print();

    // 释放链表节点内存
    Node *curr = head;
    Node *nextNode;

    while (curr != NULL) {
        nextNode = curr->next;
        free(curr);
        curr = nextNode;
    }
 
    return 0;
}

在这个代码中,我们实现了一个双向链表,并且使用插入排序对链表进行排序。首先,通过 add() 函数将输入的人员类型添加到链表中。然后使用 print() 函数打印当前排队顺序。接下来,使用 sort() 函数对链表进行排序。最后,再次使用 print() 函数打印排序后的顺序。注意,在程序结束前需要释放链表节点所占用的内存空间。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=8931

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?