实现双链表的排序

实现双链表的排序:

方法一:

就是不变动节点,只把节点中数据进行交换。

采用选择排序法:

 

#include 
using namespace std;

typedef struct DouLinkNode
{
    int data ;
    struct DouLinkNode *pre ,*next;
}node;

node *create(int n)
{   
    int x;
    node *head = new node();
    node *p,*s;
    p = head;
    p->pre = NULL;
    while(n)
    {
        s = new node();
        printf("input x:");
        scanf("%d",&x);
        s->data = x;
        p->next = s;
        s->pre = p;
        p = s;
        n--;
    }
    s->next = NULL;
    return head;
}

void display(node *head)
{
    node *p = head->next;
    while(p)
    {
        cout<data;
        p = p->next;
    }
    cout<next ;p->next!=NULL ;p=p->next)
	{
		min = p ;
		for(s= p->next ; s!=NULL ;s=s->next)
		{
			if(s->data data)
			{
				min = s;//找到每次排序中最小的节点,然后记住这个节点
			}
		}
		if(min != p)//把这个节点与前面的节点的数据进行交换,把最小的数据放在前面的节点内。
		{
			tmp = min->data;
			min->data = p->data;
			p->data = tmp;
		}
	}
	return head;

}
void main()
{
    node *head,*head1;
    int n;
    printf("input n:");
    scanf("%d",&n);
    head = create(n);
    display(head);
    head1 = paixu(head);
    display(head1);
}


方法二 采用选择排序,但交换的是节点

 

#include 
using namespace std;

typedef struct DouLinkNode
{
    int data ;
    struct DouLinkNode *pre ,*next;
}node;

node *create(int n)
{   
    int x;
    node *head = new node();
    node *p,*s;
    p = head;
    p->pre = NULL;
    while(n)
    {
        s = new node();
        printf("input x:");
        scanf("%d",&x);
        s->data = x;
        p->next = s;
        s->pre = p;
        p = s;
        n--;
    }
    s->next = NULL;
    return head;
}

void exchange( node * p, node * min )
{
    if(p==min)
        return;
    //p和min相邻要改6个指针,不相邻该8个指针
    if( min != p->next )
    {
        p->next->pre = min;
        min->pre->next = p;
    }

    p->pre->next = min;
    if( min->next != NULL)
        min->next->pre = p;

    node *min_pre = min->pre;
    node *p_next = p->next;
    min->pre = p->pre;
    p->next = min->next;

    if( min == p_next ) //p和min相邻
    {
        min->next = p;
        p->pre = min;
    }
    else
    {
        min->next = p_next;
        p->pre = min_pre;
    }

}

node* paixu(node *head)
{

    //选择排序,每一轮选择最小元素节点的和p节点交换
    for(node *p=head->next; p->next!=NULL; p=p->next)
    {
        node *min = p; //初始化最小节点
        for(node *s=p->next; s!=NULL; s=s->next)
        {
            //找最小元素的节点
            if( s->data < min->data )
                min = s;
        }
        exchange( p, min ); //交换两个节点
        p=min;//交换两个节点后,p变到了min的位置,为了遍历,把节点p重新在移动到上次节点处,即p = min;
    }

    

    return head;
}

void display(node *head)
{
    node *p = head->next;
    while(p)
    {
        cout<data;
        p = p->next;
    }
    cout<

你可能感兴趣的:(算法+数据结构)