根据您提供的代码片段,我检查了逻辑,并给出了修正后的代码如下:
#include <stdio.h>
typedef struct Node {
int type;
struct Node* prev;
struct Node* next;
} Node;
Node* head = NULL;
void print() {
Node* curr = head;
int count = 0;
printf("当前排队顺序:");
while(curr != NULL) {
printf("%d号:%d ", count, curr->type);
curr = curr->next;
count++;
}
printf("当前人数:%d\n", count);
}
void sort() {
Node* curr = head;
Node* next;
while(curr != NULL) {
next = curr->next;
while(next != NULL && next->type < curr->type) {
Node* temp = next;
next = next->next;
if(curr == head) {
head = temp;
}
else {
curr->prev->next = temp;
}
if (temp->next != NULL) {
temp->next->prev = curr;
}
temp->prev = curr->prev;
temp->next = curr;
curr->prev = temp;
}
curr = next;
}
}
int main() {
// 初始化节点并添加到链表中
Node node1, node2, node3, node4;
node1.type = 3;
node1.prev= NULL;
node1.next= &node2;
node2.type= 1;
node2.prev= &node1;
node2.next= &node3;
node3.type= 4;
node3.prev= &node2;
node3.next= &node4;
node4.type= 2;
node4.prev= &node3;
node4.next= NULL;
head = &node1;
printf("排序前:\n");
print();
sort();
printf("排序后:\n");
print();
return 0;
}
在 main()
函数中,我们初始化了节点并添加到链表中,然后调用 sort()
函数对链表进行排序。最后,通过调用 print()
函数来打印排队顺序和人数。
请注意,在修正代码时,我添加了一些缺少的指针操作,以确保链表节点的连接正确。
内容由零声教学AI助手提供,问题来源于学员提问