08单链表的正向排序

来源:互联网 发布:c语言floor函数 编辑:程序博客网 时间:2024/06/05 03:14

运行的结果如下所示:

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");
}