zoukankan      html  css  js  c++  java
  • 链表的排序 (选择和冒泡)

    无聊写了个单链表排序,不是很难。但是插入写起来很麻烦,都没有,本文全部是将链表中节点值互换,不改变结构,所以很容易写出来
    #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<<"	";
            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;
    }
  • 相关阅读:
    C# Nugut CsvHelper 使用
    C# 读写txt
    Js打开QQ聊天对话窗口
    Js 读写Cookies
    js 计算时间差
    C# 读取CSV文件
    使用 SqlBulkCopy 批量插入数据
    sql 添加列并设置默认值
    C# 获取Enum 描述和值集合
    SQL连接其它服务器操作
  • 原文地址:https://www.cnblogs.com/hansongjiang/p/3746325.html
Copyright © 2011-2022 走看看