用直接插入排序法对单链表进行排序
来源:互联网 发布:阿里云 ecs 建站 教程 编辑:程序博客网 时间:2024/06/05 13:35
#include <stdio.h>
typedef struct node
{
int key;
struct node *next;
}SNode;
void CreateLink (SNode *h,int R[],int n)//创建带头结点的单链表
{
int i;
SNode *s, *r;
h = (SNode *)malloc (sizeof (SNode));//采用尾插法建立链表
r = h; //r始终指向尾结点
for (i = 0; i < n; i++)
{
s = (SNode *)malloc (sizeof (SNode));
s->key = R[i];
r->next = s;
r = s;
}
r->next = NULL;
}
void InsertSortl(SNode *h)//采用直接插入排序法对单链表进行排序
{
SNode *p, *p1, *q, *pre;
if (h->next != NULL)//链表中至少有一个结点
{
p = h->next->next; //p指向第二个数据结点
h->next->next = NULL;//产生只带一个结点的有序表
while (p != NULL)
{
pre = h;
q = pre->next; //pre指向*p的前驱结点
while (q != NULL && q->key<p->key)
{
pre = q;
q = q->next;
}
p1 = p->next;
p->next = pre->next;//将*p插入到*pre之后
pre->next = p;//将剩余的n-1各节点进行比较后一一有序的插入到h中,
p = p1;
}
}
}
void Display (SNode *h)
{
SNode *p = h->next;
while (p != NULL)
{
printf ("%3d",p->key);
p = p->next
}
printf ("\n");
}
main ()
{
int a[] = {4,3,7,2,1,9,8,6,5,10};
int n = 10;
SNode *h;
CreateLink (h,a,n);//创建单链表
printf ("排序前:");
Display(h);
InsertSortl(h;)
printf ("排序后:");
Display (h);
}
思想同对数组进行直接插入排序一样,把链表的第一个数当做是已经排好序的,并从建立好的链表中分离出来,与剩下的n-1个结点一一比较,并进行插入。
- 用直接插入排序法对单链表进行排序
- 用直接插入法进行数组排序
- 对数组进行直接插入排序
- 输入10个整数,用直接插入法对其进行排序;
- 对字符串进行直接插入排序、堆排序、归并排序、快速排序实现以及性能分析
- 单链表直接插入排序
- 单链表---直接插入排序
- 直接插入排序法
- 直接插入排序法
- 直接插入排序法
- 直接插入法排序
- // 直接插入排序法
- 直接插入排序法
- 直接插入排序法
- 直接插入法排序
- 直接插入法排序
- 直接插入排序法
- 直接插入排序法
- poj 3616 Milking Time dp+树状数组
- How to determine the correct setting for JOB_QUEUE_PROCESSES (Doc ID 578831.1)
- 计算机管理没有mysql服务项的解决方法
- 笔试题:Suggest a simple and fast way to multiply the input integer digit by 7。
- 算法-回溯
- 用直接插入排序法对单链表进行排序
- C语言查找最大值和最小值递归实现
- 查看Linux服务器版本
- linux通信机制总结
- mybatis配置文件写法
- 将HIBITMAP保存为bmp图片
- linuxrc与inittab的作用?
- leetcode Read N Characters Given Read4
- 最简单的视频编码器:基于libx265(编码YUV为H.265)