链表中冒泡起不到效果???
#include <stdio.h>#include <malloc.h>
#include <stdlib.h>
typedef struct node
{
int date;//数据域
struct node * pnext;//指针域
}NODE,*PNODE;//NODE等价于struct node,PNODE等价于struct node *;
//声明
PNODE creat_list(void);//创建一个链表,
void traverse_list(PNODE phead);
//bool is_empty(PNODE phead);
int list (PNODE phead);
void sort_list(PNODE );
int main()
{
PNODE phead = NULL;
phead = creat_list();//创建一个链表,把头结点的地址赋给phead;
traverse_list(phead);
int len = list (phead);
printf("链表长度为len = %d:\n",len);
sort_list(phead);
/*if (is_empty(phead))
printf("次链表为空\n");
else
printf("此链表不空\n");*/
return 0;
}
PNODE creat_list(void)
{
int len;//存放有效节点的个数
int i;
int val;//临时存放用户输入的节点的值
//动态构造头结点
PNODE phead = (PNODE)malloc(sizeof(NODE));
if (NULL == phead)
{
printf("分配失败!");
exit(-1);
}
PNODE ptail = phead;//构造尾节点
ptail->pnext = NULL;
printf("请输入节点的个数:len = ");
scanf("%d",&len);
for (i=0; i<len; i++)
{
printf("请输入第%d个节点的个数:",i+1);
scanf("%d",&val);
//动态构造一个新节点
PNODE pnew = (PNODE)malloc(sizeof(NODE));
if (NULL == pnew)
{
printf("分配失败!!\n");
exit(-1);
}
pnew->date = val;
ptail->pnext = pnew;//新节点挂在尾节点后
pnew->pnext = NULL;
ptail = pnew;
}
return phead;
}
/*bool is_empty(PNODE phead)
{
if (NULL==phead->pnext)
return true;
else
return false;
}*/
int list (PNODE phead)
{
int len = 0;
PNODE p = phead->pnext;
while (NULL != p)
{
len ++;
p = p->pnext;
}
return len;
}
//冒泡排序
void sort_list(PNODE phead)
{
int i,j,t;
PNODE p,q;
int len = list (phead);
for (i=0,p=phead->pnext; i<len-1; i++,p=p->pnext)
{
for (j=i+1,q=p->pnext; j<len;j++,q=q->pnext)
{
if (p->date > q->date)
{
t = p->date;
p->date = q->date;
q->date = t;
}
}
}
}
void traverse_list(PNODE phead)
{
PNODE p = phead->pnext;
while (NULL != p)
{
printf("%3d",p->date);
p = p->pnext;
}
printf("\n");
return ;
}