单向列表插入排序

 

#include<iostream>
#include <stdlib.h>
#include <algorithm>  //调用sort函数必备;
#include <vector>
#include<cstring> 
using namespace std;


struct list
{   long id;
	char name [20];
	char sex[20];
	int age;
	list * next;
	
};
list * head;
list *getnode(){
	long id1;
	char name1[20];
	char sex1[20];
	int age1;
	cin>>name1;
	cin>>id1;
	cin>>sex1;
	cin>>age1;
	list *p=new list;
 	strncpy(p->name,name1,19);
	p->id=id1;
strncpy(p->sex,sex1,10);
	p->age=age1;
	return p;
	
	
}

class Solution {
public:
    void bubbleSort(list *head, int n){
        if(!head || !head->next) return;
        for(int i = 0; i < n; ++i){
            auto pre = head;
            auto cur = head->next;
            bool flag = 0;
            for(int j = 0; j < n-i-1; ++j){
                if(cur != NULL && pre->id> cur->id){
                    swap(pre->id, cur->id);
                    swap(pre->name,cur->name);
                     swap(pre->age,cur->age);
                      swap(pre->sex,cur->sex);
                    flag = 1;
                }
                pre = pre->next;
                cur = cur->next;
            }
            if(!flag)   break;
        }
    }
    static void create (){
	if((head=getnode())==0)
	return ;
	int i=0;
	for(list *pe=head,*ps;ps=getnode();pe=ps){
	if(i==9)break;
	pe->next=ps;
	++i;
		
}
}
    list* sortList(list* head) {
        auto p = head;
        int n = 0; // 记录节点个数
        while(p != NULL){
            ++n;
            p = p->next;
        }
        bubbleSort(head, n);
        return head;
    }
    void show (){
    	list *p=head;
    	cout<<"After ordering(id|age|name|sex)"<<endl;
    	for(int u=0;u<10;u++){
    		cout<<"(";
    		cout<<p->id<<"";
    	cout<<"|";
    		cout<<p->age<<"";
    		cout<<"|";
    		
    		
    		cout<<p->name<<"";
    	cout<<"|";
    			 
    		cout<<p->sex<<"";
    	//	cout<<"|";
    			cout<<")";
    		cout<<endl;
    		p=p->next;
					}
    	
	}
};
class Solution2 {
	public:
	 
		void show  (const list * p){
			cout<<"Before ordering(id|age|name|sex)"<<endl;
			for(int io=0;io<10;io++){
				cout<<"("<<p->id<<"|"; 
				cout <<p->age<<"|"; 
				cout <<p->name<<"|"; 
				cout <<p->sex<<")"; 
					cout<<endl;
				p=p->next;
			} 
		}
		
	
};
class Solution3 {
	public:
	 
		void show  (const list * p){
			cout<<"Before?ordering(id|age|name|sex)";
			for(int io=0;io<10;io++){
				cout<<"("<<p->id<<"|"; 
				cout<<"("<<p->age<<"|"; 
				cout<<"("<<p->name<<"|"; 
				cout<<"("<<p->sex<<"|"; 
				cout<<endl;
				p=p->next;
			} 
		}
		
	
};
int main(){
//	for(int u=0;u<10;u++)
 
 Solution aa;
 aa.create();Solution2 bb;
 bb.show(head);
 
 aa.bubbleSort(head,10);
 aa.show();
	
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值