/************************************************************************/
/* @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指向下一个待比较节点
}
}
实战数据结构(10)_单链表的就地排序
最新推荐文章于 2022-11-06 18:04:49 发布