/* 下面是用队列形式建的链表,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");
}