链表的排序 (选择和冒泡)

无聊写了个单链表排序,不是很难。但是插入写起来很麻烦,都没有,本文全部是将链表中节点值互换,不改变结构,所以很容易写出来
#include<iostream>
using namespace std;
struct node
{
    int n;
    struct node* next;

};
//创建链表
void swap(int &a,int &b)
{
    int c=a;
    a=b;
    b=c;
}
node* create(int a[],int len)
{
    if(len==0) return NULL;
     node *head=new node;
     head->n=a[0];
     head->next=NULL;
    
     node *tail=head;
     for(int i=1;i<len;i++)
     {
        node *temp=new node;
        temp->n=a[i];
        temp->next=NULL;
        tail->next=temp;
        tail=temp;


        
        
     }

      return head;

}
void display(node *head)
{
    node *p=head;
    while(p!=NULL)
    {
        cout<<p->n<<"\t";
        p=p->next;
    
    }

    cout<<endl;

}
//冒泡
void bubble(node *head)
{
    if(head==NULL) return;
    node *end=NULL;
    
    while(end!=head)
    {
        node *p=head;
    node *pnext=head->next;
        while(pnext!=end)
        {
            if(p->n>pnext->n)
            {
                swap(p->n,pnext->n);
            
            }
            p=p->next;
            pnext=pnext->next;
        
        
        }
        end=p;
    
    
    }





}
void choose(node *head)
{

    node *beg=head;
    while(beg->next!=NULL)
    {
        node *p=beg->next;
        while(p!=NULL)
        {
            if(p->n<beg->n)
            {
            swap(p->n,beg->n);
            }
        
            p=p->next;
        }

        

        beg=beg->next;
    
    }



}

int main()
{
    int a[]={2,3,4,-5,2,44,23};
    int len=sizeof(a)/sizeof(int);
    node *head=create(a,len);
    cout<<"选择排序"<<endl;
    choose(head);
    display(head);
    cout<<"冒泡排序"<<endl;
    bubble(head);
    
    display(head);
    system("pause");

    return 0;
}
posted @ 2014-05-22 19:06  hansongjiang8  阅读(247)  评论(0编辑  收藏  举报