|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
求助为何链表编译通过,排序(sort_list)这个功能却不能工作?
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
typedef struct Grade
{
int data;
struct Grade * pNext;
}GRADE,* PGRADE;
PGRADE create_list(void);
void traverse_list(PGRADE pHead);
bool is_empty(PGRADE pHead);
int length_list(PGRADE pHead);
void sort_list(PGRADE);
int main(void)
{
PGRADE pHead=create_list();
if(is_empty(pHead))
printf("The list is emoty!\n");
else
traverse_list(pHead);
int len = length_list(pHead); //************非常重要
printf("链表长度是:%d \n",len);
sort_list(pHead);
traverse_list(pHead);
return 0;
}
PGRADE create_list(void)
{
int i;
int len;
int val;
PGRADE pHead=(PGRADE)malloc(sizeof(GRADE));
printf("please enter the number of elements in your list: ");
scanf("%d",&len);
PGRADE pTail=pHead;
pTail->pNext=NULL;
for(i=0;i<len;i++)
{
PGRADE pNew=(PGRADE)malloc(sizeof(GRADE));
printf("The %d th number is : \n",i+1);
scanf("%d",&val);
pNew->data=val;
pNew->pNext=NULL;
pTail->pNext=pNew;
pTail=pNew;
}
return pHead;
}
void traverse_list(PGRADE pHead)
{
PGRADE p=pHead->pNext;
while(NULL!=p)
{
printf("%d ",p->data);
p=p->pNext;
}
printf("\n");
}
bool is_empty(PGRADE pHead)
{
if(pHead->pNext==NULL)
return true;
else
return false;
}
int length_list(PGRADE pHead)
{
PGRADE p=pHead->pNext;
int len=0;
while(NULL!=p) //*********不是p->pNext
{
++len;
p=p->pNext;
}
return len;
}
void sort_list(PGRADE pHead)
{
int i,j,t;
PGRADE p,q;
int len=length_list(pHead);
for(i=0,p=pHead->pNext;i<len-1;++i,p=p->pNext)
{
for(j=j+1,q=p->pNext;j<len;++j,q=q->pNext)
{
if(p->data>q->data)
{
t=p->data;
p->data=q->data;
q->data=t;
}
}
}
return;
}
|
|