下面是对链表进行插入排序,怎么可能不行呢?估计是排序函数有问题,其他函数应该没事,都看看那不行
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
char data;
struct node *priorPtr;
struct node *nextPtr;
}*LinkList, Lnode; /* 单链表结构 */
static void CreateList(LinkList *headPtr, LinkList *tailPtr, char ch);
static void InsertSort(LinkList *headPtr);
static void Traverse(LinkList headPtr);
static void DestroyList(LinkList *headPtr, LinkList *tailPtr);
int main(void)
{
LinkList headPtr = NULL, tailPtr = NULL;
char ch;
printf("Enter ch('@' quit): ");
scanf(" %c", &ch);
while (ch != '@')
{
CreateList(&headPtr, &tailPtr, ch); /* 创建链表 */
printf("continue enter: ");
scanf(" %c", &ch);
}
Traverse(headPtr); /* 打印排序前顺序 */
if (headPtr != NULL) /* 链表不空的情况下对链表进行插入排序 */
{
InsertSort(&headPtr);
}
else
{
printf("The list is empty.\n");
}
Traverse(headPtr); /* 打印排序后的顺序 */
if (headPtr != NULL) /* 释放所分配的内存空间 */
{
DestroyList(&headPtr, &tailPtr);
}
else
{
printf("The list is empty.\n");
}
return 0;
}
static void CreateList(LinkList *headPtr, LinkList *tailPtr, char ch)
{
LinkList newPtr;
if ((newPtr = (LinkList)malloc(sizeof(Lnode))) == NULL)
{
exit(1);
}
newPtr -> data = ch;
newPtr -> priorPtr = NULL;
newPtr -> nextPtr = NULL;
if (*headPtr == NULL) /* 空表情况下 */
{
newPtr -> priorPtr = *headPtr;
newPtr -> nextPtr = *headPtr;
*headPtr = newPtr;
}
else /* 非空情况下 */
{
(*tailPtr) -> nextPtr = newPtr;
newPtr -> priorPtr = *tailPtr;
newPtr -> nextPtr = NULL;
}
*tailPtr = newPtr;
}
static void InsertSort(LinkList *headPtr) /* 插入排序 */
{
LinkList pA,pB;
char temp;
/* 按数组的形式进行插入排序,下面有问题,看不出来啊 */
for (pA = *headPtr; pA -> nextPtr != NULL; pA = pA -> nextPtr)
{
if (pA -> data > pA -> nextPtr -> data) /* 当前结点数据大于下一结点数据 */
{
temp = pA -> nextPtr -> data;
for (pB = pA; pB != NULL; pB = pB -> priorPtr)
{
if (pB -> data > temp)
{
pB -> nextPtr -> data = pB -> data;
}
else
{
break;
}
}
pB -> nextPtr -> data = temp;
}
}
}
static void Traverse(LinkList headPtr) /* 打印函数 */
{
while (headPtr != NULL)
{
printf("%c -> ", headPtr -> data);
headPtr = headPtr -> nextPtr;
}
printf("NULL\n");
}
static void DestroyList(LinkList *headPtr, LinkList *tailPtr)
{
LinkList tempPtr;
while (*headPtr != NULL) /*释放内存空间 */
{
tempPtr = *headPtr;
*headPtr = (*headPtr) -> nextPtr;
free(tempPtr);
}
*headPtr = NULL;
*tailPtr = NULL;
}