单链表的实现(创建+排序(选择))

 

#include <iostream>
#include <malloc.h>
using namespace std;
typedef struct Lnode
{
    Lnode *next;
    int data;
}Lnode,*pLnode;
pLnode createList(int n)
{
    Lnode*head=(Lnode*)malloc(sizeof(Lnode));
    head->next=NULL;
    Lnode *p=NULL;
    pLnode temp=head;
    for(int i=0;i<n;i++)
    {
       p=(Lnode*)malloc(sizeof(Lnode));
       p->next=NULL;

       cin>>p->data;
       temp->next=p;
       temp=p;
    }
    return head;
}
void print(pLnode head)
{
    pLnode p=head->next;
    while(p)
    {
        cout<<p->data<<" ";
        p=p->next;
    }
}
void selectSort(Lnode*head)
{
    Lnode *p=NULL;
    Lnode *q=NULL;
    Lnode *small=NULL;
    for(p=head->next;p;p=p->next)
    {
        small=p;
        for(q=p->next;q;q=q->next)
        {
            if(q->data<small->data)
            {
                small=q;
            }
        }
        if(small!=p)
        {
            int temp=p->data;
            p->data=small->data;
            small->data=temp;
        }

    }

}
int main()
{
    pLnode temp=NULL,head=NULL;
    head=createList(10);
    print(head);
    cout<<endl;
    selectSort(head);
    print(head);
    return 0;
}

 

posted @ 2017-09-07 14:43  泡面小王子  阅读(341)  评论(0编辑  收藏  举报