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();
 
  return 0;
}

修复了插入排序的逻辑和指针操作,现在代码应该可以正确地对双向链表进行排序并输出结果。


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

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?