08单链表的正向排序

运行的结果如下所示:

010单链表的正向排序 - 458905216 - SaEe的博客
代码如下所示:
#include <stdio.h>
#include <malloc.h>
/*单链表的正向排序*/
typedef struct node
{
int data;
struct node *next;
}node;
node *InsertSort(void)
{
int data = 0;
struct node *head = NULL , *New , *Cur , *Pre;
while(1)
{
printf("please input the data:\n");
scanf("%d" , &data);
if(data == 0)
{
break; /*输入0结束*/
}
New = (struct node*)malloc(sizeof(struct node));
New->data = data; /*新分配一个node节点*/
New->next = NULL;

if(head == NULL)
{ /*第一次循环时对头节点赋值*/
head = New;
continue;
}

if(New->data <= head->data)
{
/*head之前插入节点*/
New->next = head;
head = New;
continue;
}
Cur = head;
while(New->data > Cur->data && Cur->next != NULL) /*找到需要插入的位置*/
{
Pre = Cur;
Cur = Cur->next;
}
if(Cur->data >= New->data) /*位置在中间*/
{
Pre->next = New;
New->next = Cur; /*new节点插入到Pre和Cur之间*/
}
else /*位置在末尾*/
{
Cur->next = New; /*把new节点插入到cur之后*/
}
}
return head;
}
void print(node *head)
{
node *p;
if(head == NULL)
{
printf("The Link is empty!\n");
return;
}
p = head;
while(p != NULL)
{
printf("%d " , p->data);
p = p->next;
}
}
void main()
{
node *head = InsertSort();

print(head);
printf("\n***********************************\n");
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值