C语言:实现单条链表排序和倒序

代码如下:

/****************************************************
*功能:随机数插入链表,实现单条链表排序和倒序
*作者:lml   时间:2020年4月15日20:25:40
****************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define dtype int

typedef struct test{
    
    
	dtype data;
	struct test* next;
}link,*link_p;

//开辟空间
link_p do_malloc()
{
    
    
	link_p S=NULL;
	S = (link *)malloc(sizeof(link));
	if(S == NULL){
    
    
		printf("malloc fail!\n");
		return NULL;
	}

	return S;
}

//插入函数
int do_insert(link_p S,dtype val)
{
    
    
	link_p M=NULL;
	M = (link *)malloc(sizeof(link));
	if(M == NULL){
    
    
		printf("insert malloc fail!\n");
		return -1;
	}
	M->next = S->next;
	S->next = M;
	M->data = val;

	return 0;
}
//打印函数
int do_show(link_p S,char *name)
{
    
    
	link_p M = S->next;

	printf("%s:data:",name);
	while(M != NULL){
    
    
		printf("%02d  ",M->data);
		M = M->next;
	}
	putchar(10);
	return 0;
}

//随机数函数
int do_srand()
{
    
    
	int a;
	srand((unsigned)time(0));
	a = rand()% 100 + 1;
	return a;
}

//链表排序,冒泡排序
int do_ranking(link_p S){
    
    
	dtype temp;
	link_p M = S->next;
	link_p N = S->next;
	
	for(M=S->next;M->next!=NULL;M=M->next){
    
    
		for(N=S->next;N->next!=NULL;N=N->next){
    
    
			if(N->data >= N->next->data){
    
    
				temp = N->next->data;
				N->next->data = N->data;
				N->data = temp;	
			}
		}
	}
	return 0;
}

//链表倒序
int do_reverse(link_p S)
{
    
    
	link_p M = S;               //头位置
	link_p T = S->next->next;   //把第二个节点地址取出来
	link_p N = S->next;         //把第一个的地址保存,因为它最后会变成尾巴,需要赋空值
	link_p Q= NULL;             //临时中转用的
	while(T != NULL){
    
               //开始重组节点
		Q = M->next;            //把第头节点的下一个的地址保存
		M->next = T;            //把头节点连向第二节点
		T = T->next;            //第二个几点地址已经用到了,先让T指针指向下一个节点
		M->next->next = Q;      //第二个节点尾部指向第一个节点,这一步必须在上一部之后
	}
	N->next = NULL;             //上面T指针会自动在循环中往下走,最后把尾巴指向空

	return 0;
}


//销毁链表
int do_freelink(link_p S)
{
    
    
	link_p M=S;

	while(M!= NULL){
    
    
		S=M->next;
		free(M);
		M=S;
	}
	S=NULL;
	return 0;
}

//主函数
int main(int argc, const char *argv[])
{
    
    
	int i=0;

	link_p L,G;
	if((L = do_malloc()) == NULL){
    
    
		printf("main do_malloc fail!\n");
		return -1;
	}
	
	//插入链表,随机数插入
	for(i=1;i<=5;i++){
    
    
		do_insert(L,do_srand());
		usleep(1000000);
	}
	
	do_show(L,"LL");
	
	printf("ranking:\n");
	
	//开始排序
	do_ranking(L);	
	do_show(L,"LL");
	
	//倒序
	do_reverse(L);
	do_show(L,"LL");

	//销毁链表
	do_freelink(L);
	return 0;
}

结束。

猜你喜欢

转载自blog.csdn.net/qq_19693355/article/details/105693886
今日推荐