泡末排序不太好,插入排序单链解决不了,惟选择排序绝佳(个人认为)
#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 ExchangeSort(LinkList *headPtr);
static void Traverse(LinkList headPtr);
int main(void)
{
LinkList headPtr = NULL, tailPtr = NULL;
int item;
printf("Enter item: ");
scanf("%d", &item);
while (item != 0)
{
CreateList(&headPtr, &tailPtr, item);
printf("Enter item: ");
scanf("%d", &item);
}
Traverse(headPtr);
if (headPtr != NULL)
{
ExchangeSort(&headPtr);
Traverse(headPtr);
}
else
{
printf("list is empty.\n");
}
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 ExchangeSort(LinkList *headPtr)
{
LinkList currentPtrA, currentPtrB;
int temp;
for (currentPtrA = *headPtr; currentPtrA -> nextPtr != NULL; currentPtrA = currentPtrA -> nextPtr)
{
for (currentPtrB = currentPtrA -> nextPtr; currentPtrB != NULL; currentPtrB = currentPtrB -> nextPtr)
{
if (currentPtrA -> data > currentPtrB -> data)
{
temp = currentPtrA -> data;
currentPtrA -> data = currentPtrB -> data;
currentPtrB -> data = temp;
}
}
}
}
static void Traverse(LinkList headPtr)
{
while (headPtr != NULL)
{
printf("%d -> ", headPtr -> data);
headPtr = headPtr -> nextPtr;
}
printf("NULL\n\n");
}