写了一个随机双向链表,排序操作有问题,导致我在进行排序的时候,总是会出现一个不知道哪来的数,请大家帮我看看是函数写的有问题还是在创建链表的时候我多创了空间导致他自己写了个数在里面。
这个是我写的结构体:
typedef struct ltbl
{
struct ltbl* pPre; //前一个
struct ltbl* pNxt; //后一个
int nKey; //结点里的值
unsigned char ucDummy[32]; //备用
}LTBL;
typedef struct mng
{
int nNodeCnt; //链表长度
LTBL* pHead; //指向头指针
}MNG;
这里是我的创建和排序:
int TBLCreate (MNG* pMng, int nCnt)
{
int i;
LTBL* head = NULL;
LTBL* p = NULL;
LTBL* q = NULL;
head = (LTBL*)malloc(sizeof(LTBL));
pMng->pHead = head;
srand((unsigned int)time(0));
pMng->nNodeCnt = nCnt;
if(NULL == head)
{
printf("WRONG!");
return NG;
}
head->pPre = NULL;
head->nKey = rand() % 200;
head->pNxt = NULL;
p = head;
for(i=1; i<=pMng->nNodeCnt; ++i)
{
q = (LTBL*)malloc(sizeof(LTBL));
if(NULL == q)
{
printf("WRONG!");
return NG;
}
q->nKey = rand() % 200;
p->pNxt = q;
q->pPre = p;
q->pNxt = NULL;
p = q;
}
q->pNxt = NULL;
return OK;
}
void TBLSort(MNG* pMng, int nFlg)
{
int t = 0;
LTBL* head;
LTBL* p = NULL;
LTBL* q = NULL;
head = pMng->pHead;
if(0 == nFlg)
{
for(p=head; p!=NULL; p=p->pNxt)
{
for(q=p->pNxt; q!=NULL; q=q->pNxt)
{
if(p->nKey > q->nKey)
{
t = q->nKey;
q->nKey = p->nKey;
p->nKey = t;
}
}
}
}
if(1 == nFlg)
{
for(p=head; p!=NULL; p=p->pNxt)
{
for(q=p->pNxt; q!=NULL; q=q->pNxt)
{
if(p->nKey < q->nKey)
{
t = q->nKey;
q->nKey = p->nKey;
p->nKey = t;
}
}
}
}
Print(pMng);
}