求一个动态链表冒泡排序(指针域交换)的小例,说明详细一点,调用系统函数要说明的,谢谢了。

2025-06-22 17:23:19
推荐回答(2个)
回答1:

#include
#include
#include
typedef struct node{
    int data;
    struct node *next;
}Node;
Node *head;
void ini(int n){
    Node *p, *q;
    q = head;
    printf("请输入n个整数:\n");
    while(n--){
        p = (Node*)malloc(sizeof(Node));
        scanf("%d", &(p->data));
        p->next = NULL;
        q->next = p;
        q = p;
    }
}
void BubleSort(Node *h, int len){
    Node *p, *q;
    int i;
    while(len--){
        p = head->next, q = p->next; h = head;
        for(i = 0; i < len && q != NULL; ++i){
            if(p->data > q->data){
                h->next = q;
                p->next = q->next;
                q->next = p;
                h = q; q = p->next;
            }
            else{
                h = h->next;  p = p->next;  q = q->next;
            }
        }
    }
}
void Print(Node *h){
    Node *p = h->next;
    while(p != NULL){
        printf("%d ", p->data);
        free(h);
        h = p; p = p->next;
    }
    printf("\n");
}
int main(){
    int n;
    printf("请输入一个大于0的整数n: ");
    scanf("%d", &n);
    head = (Node*)malloc(sizeof(Node));  //头结点指向一个空的节点
    if(n > 0)
        ini(n);  //初始化建立链表
    else{
        printf("n必须是一个大于0的整数!\n");
        return 0;
    }
    BubleSort(head, n);  //冒泡排序,第一个参数是链表的头节点,第二个参数是链表的长度
    Print(head);  //输出
    return 0;
}

代码写的有一点乱,不过还好。你先看看不懂可以问我!让你懂为止。

回答2:

链表相对于 普通的指针交换冒泡,就是就多了额外的一个指针而已,把原本的数组内容变成结构体就OK了~。。。。