【测试数据】这里为了方便,采用用文件读入方式
4 5 2 1 3 3 2 4 7
【代码】
#include <stdio.h>
#include <stdlib.h>
typedef struct LNode
{
int data;
struct LNode* next;
}LNode;
//采用直接插入法排序,且与序列中值相等的元素不重复插入
void InsertSort(LNode* L, int x)
{
LNode* p, *s;
p = L;
//创建一个结点s
s = (LNode*)malloc(sizeof(LNode));
s->data = x;
s->next = NULL;
//找到刚好比x大的结点,该结点可能大于x,也可能等于x
while (p->next != NULL && p->next->data < x)
{
p = p->next;
}
//找不到比x大的结点,x可以之间插在链表后面
if (p->next == NULL)
{
p->next = s;
}
else if(p->next->data > x)
{
s->next = p->next;
p->next = s;
}
//如果找到的结点与x相等则什么都不做
}
LNode* CreateList()
{
LNode* L;
int x;
FILE* fp;
if ((fp = fopen("data.txt", "r")) == NULL)
{
exit(0);
}
//构建一个头结点
L = (LNode*)malloc(sizeof(LNode));
L->next = NULL;
while (fscanf(fp, "%d", &x) != EOF)
{
InsertSort(L, x);
}
return L;
}
void PrintList(LNode* L)
{
LNode* p;
p = L->next;
while (p)
{
printf("%d ", p->data);
p = p->next;
}
}
int main()
{
LNode* L;
L = CreateList();
PrintList(L);
return 0;
}