/* 下面是用队列形式建的链表,BubbleSort函数现在有问题不能对
链表进行排序 */
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node *nextPtr;
}*LinkList, Lnode;
static void CreateList(LinkList *headPtr, LinkList *tailPtr, int item);
static void BubbleSort(LinkList *headPtr);
static void Traverse(LinkList headPtr); /* print function */
int main(void)
{
LinkList headPtr = NULL, tailPtr = NULL; /* 头指针和尾指针*/
int item;
printf("Enter item (0 quit): ");
scanf("%d", &item);
while (item != 0) /* 0 quit */
{
CreateList(&headPtr, &tailPtr, item);
printf("Enter item(0 quit): ");
scanf("%d", &item);
}
Traverse(headPtr);
if (headPtr != NULL) /* 链表不空情况下排序*/
{
BubbleSort(&headPtr);
Traverse(headPtr);
}
getch();
return 0;
}
static void CreateList(LinkList *headPtr, LinkList *tailPtr, int item)
{
LinkList newPtr;
if ((newPtr = (LinkList)malloc(sizeof(Lnode))) == NULL)
{
printf("memory malloc failure.\n");
exit(1);
}
newPtr -> data = item;
newPtr -> nextPtr = NULL;
if (*headPtr == NULL)
{
newPtr -> nextPtr = *headPtr;
*headPtr = newPtr;
}
else
{
(*tailPtr) -> nextPtr = newPtr;
}
*tailPtr = newPtr;
}
static void BubbleSort(LinkList *headPtr) /* 我晕,就这个函数问题*/
{
LinkList tempPtr, currentPtrA, currentPtrB;
currentPtrA = *headPtr;
while (currentPtrA -> nextPtr != NULL) /* 相当于数组的外层循环 */
{
currentPtrB = *headPtr;
while (currentPtrB -> nextPtr != NULL) /* 相当于数组的内层循环 */
{
if (currentPtrB -> data > currentPtrB -> nextPtr -> data)
{
tempPtr = currentPtrB;
currentPtrB = currentPtrB -> nextPtr;
currentPtrB -> nextPtr = tempPtr;
}
currentPtrB = currentPtrB -> nextPtr;
}
currentPtrA = currentPtrA -> nextPtr;
}
}
static void Traverse(LinkList headPtr)
{
while (headPtr != NULL)
{
printf("%d -> ", headPtr -> data);
headPtr = headPtr -> nextPtr;
}
printf("NULL\n");
}
----------------解决方案--------------------------------------------------------
什么问题啊?
是不能正常结束么?
我能正常排序,就是不能正常结束,是这个问题么?
----------------解决方案--------------------------------------------------------
哦,我看错了,连排序都不正常
----------------解决方案--------------------------------------------------------
我这里不能输出排序的结果且无法结束,必须强行结束
----------------解决方案--------------------------------------------------------
tempPtr = currentPtrB;
currentPtrB = currentPtrB -> nextPtr;
currentPtrB -> nextPtr = tempPtr;
这里,构成死循环
如果输入的是a->b->c,且需要进行b和c的调换
那么经过这段程序后,会出现
a->x->b=c->x
其中x是原来b的位置
----------------解决方案--------------------------------------------------------
谢谢楼上大哥,我搞定了
----------------解决方案--------------------------------------------------------