链表排序(C语言)选择排序

#include <stdio.h>
#include <stdlib.h>
#include <time.h> //用到了time函数

#define arraySize 10


typedef int elemType;

typedef struct List
{
    elemType elem;
    struct List *next;
}Node;

//产生随机数组
void createRandomArray(int array[])
{
    int i,number;
    srand((unsigned) time(NULL)); //用时间做种,每次产生随机数不一样
    for (i=0; i<arraySize; i++)
    {
        array[i] = rand() % 101; //产生0-100的随机数
    }
}

//创建单链表
struct List *createList(int num,int arrayList[])
{
    Node *head,*p1,*p2;
    if((head=(Node*)malloc(sizeof(Node)))==NULL)
    {
        printf("create error\r\n");
        exit(0);
    }
    head->elem=0;
    head->next=NULL;
    p1=head;
    int i;
    for(i=0;i<num;i++)
    {
        if((p2=(Node*)malloc(sizeof(Node)))==NULL)
        {
            printf("create error\r\n");
            exit(0);
        }
        p2->elem=arrayList[i];
        p2->next=NULL;
        p1->next=p2;
        p1=p2;
    }
    return head;
}

//遍历单链表
void displayList(Node *head)
{
    printf("遍历链表:");
    Node *p1;
    if(head==NULL)
    {
        printf("空链表\r\n");
        //exit(0);
    }
    else
    {
        for(p1=head->next;p1!=NULL;p1=p1->next)
        {
            printf("%d\t",p1->elem);
        }
        printf("\r\n");
    }
}

//判断链表是否为空
bool isEmptyList(Node* head)
{
    return head==NULL;//||head->next==NULL;
}

//链表排序  从小到大排 选择排序
void sortList(Node* head)
{
    printf("------进行排序------\r\n");
    Node *p1,*p2,*p3,*temp;
    if((temp=(Node*)malloc(sizeof(Node)))==NULL)
    {
        printf("sort create error");
    }
    p1=head;
    //int i=0,j=0;//调试
    for(p2=p1->next;p2->next!=NULL;p2=p2->next)
    {
		for(p3=p2->next;p2!=NULL;p3=p3->next)
        {
            if(p2->elem>p3->elem)
            {
                temp->elem=p3->elem;
                p3->elem=p2->elem;
                p2->elem=temp->elem;
            }
//			i++;
//            printf("i:%d\t",i);
			if(p3->next==NULL)
				break;
        }
//		j++;
//        printf("j:%d\t",j);
	}
}

int main()
{
    Node *head;
    elemType temp;
    int arrayList[arraySize];
    createRandomArray(arrayList);
    head=createList(arraySize,arrayList);
    printf("排序前\r\n");
    displayList(head);
    sortList(head);
    printf("排序后\r\n");
    displayList(head);
    return 0;
}

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值