链表实现基础排序算法

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

/*
*用链表实现简单排序算法(交换两个节点)
*/
#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

*/
posted @ 2018-04-07 23:39  fenicnn  阅读(1214)  评论(0编辑  收藏  举报