链表实现基础排序算法

用链表实现基础的排序算法,并且要求交换两个节点,而不是两个节点的值。

/*
*用链表实现简单排序算法(交换两个节点)
*/
#include<iostream>
#include<ctime>
#include<cstdlib>
#include<cstdio>
using namespace std;
typedef struct node* Link;
typedef struct node {
    int value;
    Link next;
    node() {
        value=0;
        next=NULL;
    }
    node(int v) {
        value=v;
        next=NULL;
    }
} Node;

Link BuildList(int n) {
    Link head=new Node();
    Link current_p=head;
    for(int i=0; i<n; i++) {
        int x;
        scanf("%d",&x);
        Link p=new Node(x);
        current_p->next=p;
        current_p=current_p->next;
    }
    head->value=n;
    return head;
}

//冒泡排序
void BubbleSort(Link head) {
    int n=head->value;
    for(int i=0; i<n-1; i++) {
        Link p=head,next_p=NULL,nnext_p=NULL;
        for(int j=0; j<n-i-1; j++) {
            next_p=p->next;
            nnext_p=next_p->next;
            if(next_p->value>nnext_p->value) {
                //swap two nodes
                next_p->next=nnext_p->next;
                nnext_p->next=next_p;
                p->next=nnext_p;
            }
            p=p->next;
        }
    }
}

//选择排序
void SelectSort(Link head) {
    int n=head->value;
    Link current_p=head;
    for(int i=0; i<n-1; i++) {
        Link p=current_p->next,min_p=current_p;
        while(p->next!=NULL) {
            if(min_p->next->value>p->next->value) {
                min_p=p;
            }
            p=p->next;
        }
        if(min_p!=current_p) {
            if(current_p->next==min_p) {
                Link next_min_p=min_p->next;
                //交换两个临近点
                min_p->next=next_min_p->next;
                next_min_p->next=min_p;
                current_p->next=next_min_p;
            } else {
                //交换两个不临近点
                Link next_current_p=current_p->next;
                Link next_min_p=min_p->next;

                current_p->next=next_min_p;
                min_p->next=next_current_p;

                Link tmp_p=next_current_p->next;
                next_current_p->next=next_min_p->next;
                next_min_p->next=tmp_p;
            }
        }
        current_p=current_p->next;
    }
}

void Print(Link head) {
    head=head->next;
    while(head!=NULL) {
        printf("%d%c",head->value,head->next==NULL?'\n':' ');
        head=head->next;
    }
}

int main() {
    int n;
    while(scanf("%d",&n)==1) {
        Link head=BuildList(n);
    BubbleSort(head);
//        SelectSort(head);
        Print(head);
    }
    return 0;
}

/*test case:
2
2 1

1
1

0

5
1 3 5 2 4

5
1 2 3 4 5

5
5 4 3 2 1

5
1 2 1 2 1

*/

转载于:https://www.cnblogs.com/fenice/p/8735623.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值