#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node * pnext;
}NODE,*PNODE;
PNODE init();
void append(PNODE);
void traverse(PNODE);
int length(PNODE);
void sort(PNODE);
int main(void)
{
PNODE phead = NULL;
phead = init();
append(phead);
traverse(phead);
length(phead);
sort(phead);
traverse(phead);
return 0;
}
PNODE init()
{
PNODE phead = (PNODE)malloc(sizeof(NODE));
if(phead == NULL)
{
printf("内存分配失败,程序终止!");
exit(-1);
}
phead->pnext = NULL;
return phead;
}
void append(PNODE phead)
{
int n,val;
printf("请输入要添加几个节点");
scanf("%d", &n);
PNODE ptail = phead;
for(int i =0; i < n; i++)
{
printf("请输入第%d个节点的值", i+1);
scanf("%d", &val);
PNODE pnew = (PNODE)malloc(sizeof(NODE));
if(phead == NULL)
{
printf("内存分配失败,程序终止!");
exit(-1);
}
pnew->data = val;
ptail->pnext = pnew;
pnew->pnext = NULL;
ptail = pnew;
}
}
void traverse(PNODE phead)
{
PNODE p = phead->pnext;
while(p != NULL)
{
printf("%d ", p->data);
p = p->pnext;
}
printf("\n");
}
int length(PNODE phead)
{
PNODE p = phead->pnext;
int len = 0;
while(NULL != p)
{
len++;
p = p->pnext;
}
return len;
}
void sort(PNODE phead)
{
int t =0, i,j;
PNODE p =NULL, q = NULL;
for(i = 0,p = phead->pnext; i < length(phead)-1; i++,p = p->pnext)
{
for(j = i+1,q = p->pnext; j < length(phead); j++,q = q->pnext)
{
if(p->data > q->data)
{
t = p->data;
p->data = q->data;
q->data = t;
}
}
}
}
/*
2013年5月26日13:41:55
在VC++6.0中的运行结果
请输入要添加几个节点5
请输入第1个节点的值36
请输入第2个节点的值41
请输入第3个节点的值25
请输入第4个节点的值75
请输入第5个节点的值1
36 41 25 75 1
1 25 36 41 75
Press any key to continue
*/