实战数据结构(10)_单链表的就地排序

/************************************************************************/
/* @auhthor lynnbest
目标:单链表的排序(升序)
exp:
input:3,5,8,6,2,1         
output:1,2,3,5,6,8
                                                            */
/************************************************************************/
#include <stdio.h>
#include <stdlib.h>

typedef struct node
{
	int data;
	struct node *next;
}listnode;	//注意C++中struct 是可以单独声明类型的。和C不一样

void InsertListNode(listnode *head,int pos,int data,int len);
void printflist(listnode *head);
void SortSingleList(listnode *head);
int main()
{	

	printf("   单链表的排序	\n");
	printf("----by lynnbest ----\n\n");
	int a[]={3,5,8,6,2,1,11,45,16};
	int len=sizeof(a)/sizeof(a[0]);
	listnode *head=(listnode *)malloc(sizeof(listnode));
	if(NULL==head)
	{
		printf("头结点创建失败\n");
		exit(-1);
	}
	head->next=NULL;
	for(int i=0;i<len;i++)
		InsertListNode(head,i+1,a[i],len);
	printf("排序之前的单链表元素为:\n");
	printflist(head);
	SortSingleList(head);
	printf("排序之后的单链表元素为:\n");
	printflist(head);
	return 0;
}

void InsertListNode(listnode *head,int pos,int data,int len) //插入函数
{
	listnode *pre=head,*newnode;
	if(pos<1||pos>(len+1))
	{
		printf("插入位置error\n");
		exit(-1);
	}
	for(int i=1;i<pos;i++) //从1号位置开始计算
		pre=pre->next;
	if(NULL==(newnode=(listnode *)malloc(sizeof(listnode))))
	{
		printf("新节点创建失败\n");
		exit(-1);
	}
	newnode->data=data;
	newnode->next=NULL;
	
	newnode->next=pre->next;
	pre->next=newnode;
}

void printflist(listnode *head)//打印函数
{
	listnode *p=head->next;
	while(p!=NULL)
	{
		printf("%3d",p->data);
		p=p->next;
	}
	printf("\n");
}
/************************************************************************/
/* 思路:
将待排序的节点在已经排序号的链表中寻找插入位置(前驱位置),然后就是插入,
和准备下一次的环境
                                                                     */
/************************************************************************/
void SortSingleList(listnode *head)
{
	listnode *pre=head,*p=pre->next,*q,*r;	//pre指向head,p指向第一个元素
	q=p->next; //q指向待比较节点
	p->next=NULL;	//第一个节点next截止 NULL
	while(q!=NULL)
	{
		while(pre->next!=NULL && q->data>pre->next->data)//查找插入点的前驱节点
			pre=pre->next;
		r=q->next;	//保存待比较的下一个节点

		q->next=pre->next; 
		pre->next=q;	//插入节点
		
		pre=head;	//恢复pre的head
		q=r;	//q指向下一个待比较节点
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值