#include "stdafx.h"
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
typedef int type;
typedef struct lnode //定义链表结点的数据结构
{
int data;
struct lnode *next;
}Lnode;
typedef Lnode node;
typedef struct dnode//定义双链表结点的数据结构
{
int data;
struct dnode *lnext;
struct dnode *rnext;
}Dnode;
int posprint9(node *h)
{
//先将链表就地使用插入的方法排好序再一次输出并释放空间
node *p = h->next; node *q = p;
while (q->next)//插入法排好正序
if (q->next->data >= q->data)
q = q->next;
else
{
if (q->next->data <= p->data)
{
h->next = q->next;
q->next = q->next->next;
h->next->next = p;
// print(h);
}
else
{
while (!(p->data <= q->next->data&&p->next->data >= q->next->data))
p = p->next;
node *tem = p->next;
p->next = q->next;
q->next = q->next->next;
p->next->next = tem;
// print(h);
}
p = h->next;
}
//打印节点值并释放结点所占有的空间
p = h;
q = h->next;
while (q)
{
printf("%d ", q->data);
p = q; q = q->next;
free(p);
}
free(h);
//分析以上程序可知其时间复杂度花在遍历整个链表以及找到应插入位置的两个循环上,最差为o(n^2) 空间复杂度o(1);
//方法二:每次找到当前链表的最小值后则进行删除,重复以上操作直至链表中一个元素也不剩
// node *p,*q,*tem;
// while(h->next){
// p=h;q=p->next;
// while(q->next)
// {
// if(q->next->data<p->next->data)
// p=q;
// else
// q=q->next;
// }
// printf("%d ",p->next->data);
// tem=p->next;
// p->next=p->next->next;
// free(tem)
//}
// free(h);
return 0;
}