利用哨兵节点的链表选择排序(交换节点)

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
struct cell {//单链表结点结构体定义
    int x;
    struct cell* next;
};
struct cell* build(void) {//新建单链表,并将建好的单链表首结点地址返回
    struct cell* head, * tmp, * tail;
    head = tmp = tail = NULL;
    int n;
    /*请在以下位置补充完整,实现函数build的功能*/
    scanf("%d", &n);
    while (n != 0) {
        tmp = (struct cell*)malloc(sizeof(struct cell));
        if (head == NULL) {
            head = tmp;
        }
        else {
            tail->next = tmp;
        }
        tmp->x = n;
        tmp->next = NULL;
        tail = tmp;
        scanf("%d", &n);
    }
    return head;//返回单链表头
}
struct cell* sort_1(struct cell* head) {//递增排序链表,head是单链表首结点指针
    struct cell* p, * p0, * r, * r0, * q;
    p = p0 = r = r0 = q = NULL;
    p = head;
    if (head == NULL) {
        return NULL;
    }//空链表
    if (head->next == NULL) {
        return head;
    }//单节点
    struct cell* temp;
    temp = (struct cell*)malloc(sizeof(struct cell));
    temp->x = 0;
    temp->next = head;//链接
    head = temp;//哨兵节点作为第一个节点
    //排序从哨兵后一位开始
    p0 = head;
    p = p0->next;
    r0 = head;
    r = r0->next;//初始化
    while (p->next) {//for(int i = 0;i<n-1;i++){}
        r0 = p;
        r = p->next;
        while (r) {//for(int j = i+1;j<n;j++){}
            if (p->x > r->x) {
                r0->next = p;
                p0->next = r;//改变跟随的内容;
                q = r->next;
                r->next = p->next;
                p->next = q;//改变后面链接的内容
                r = r0->next;
                p = p0->next;//复位p,r    
            }
            else {
                r0 = r;
                r = r->next;
            }
        }
        p0 = p;
        p = p->next;  
    }
    struct cell* temp2 = head;
    head = head->next;
    free(temp2);//释放哨兵节点
    return head;
}   /*  sort */
void print(struct cell* head) {//打印整个单链表,head是单链表首结点指针
    /*请在以下位置补充完整,实现函数print的功能*/
    while (head) {
        printf("%d ", head->x);
        head = head->next;
    }
}
void release(struct cell* head) {//释放单链表空间,head是单链表首结点指针
    /*请在以下位置补充完整,实现函数release的功能*/
    struct cell* temp;
    while (head) {
        temp = head;
        head = head->next;
        free(temp);
    }
}
int main(void) {
    struct cell* head;
    head = build();
    if (head != NULL) {
        head = sort(head);
        print(head);
    }
    else
        printf("NULL");
    release(head);
    return 0;
}

  • 12
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值