以下是补全代码实现双向链表排序的示例:
#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;
}
使用插入排序算法对双向链表进行排序,按照每个节点的type值进行升序排列。
内容由零声教学AI助手提供,问题来源于学员提问