單鏈表的選擇排序


給定一個無序單鏈表,實現單鏈表的選擇排序(按升序排序)。

代碼注釋挺詳細,直接上代碼!

#include <stdio.h>
#include <stdlib.h>
struct node{
    int data;
    struct node *next;
}; 
void printList(struct node *head){
    struct node *t=head;
    while(t){
        printf("%d ",t->data);
        t=t->next;
    }
}
struct node * selectSort(struct node *head)
/*選擇排序 
在原鏈表中一輪輪地找最大的那個結點,找到之后就把它從原鏈表中抽出來用頭插法加到新的鏈表中。 
需要注意這個最大的結點是否為頭結點 
*/
{
    struct node *head1,*max,*premax,*t,*pret;
    //head1:新鏈表的頭指針;max:原鏈表中最大的結點;premax:最大結點的前驅結點;t:用於遍歷原鏈表尋找最大結點;pret:t的前驅結點
    head1=NULL;
    while(head)//一遍遍地找原鏈表中當前最大結點 
    {
        max=head;
        premax=NULL;
        pret=head;
        t=head->next;
        //1、尋找最大結點 
        while(t){
            if(t->data>max->data){
                max=t;
                premax=pret;
            }
            pret=t;
            t=t->next;    
        }
        //2、讓這個結點離開原鏈表
        if(max==head)//如果找到的結點是第一個結點
            head=head->next;//讓頭指針向后移一位就行
        else
            premax->next=max->next;
        //3、把此結點頭插法插入新鏈表
        max->next=head1;
        head1=max;
    }
    return head1;
}
int main()
{
    struct node *head,*p,*q;
    int i,n,a;
    scanf("%d",&n);
    head=NULL;
    for(i=0;i<n;i++){
        p=(struct node *)malloc(sizeof(struct node));
        scanf("%d",&a);
        p->data=a;
        p->next=NULL;
        if(!head){
            head=p;
        }else{
            q->next=p;
        }
        q=p;
    }
    printList(selectSort(head));
 } 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM