已知一个双向链表,从第2个元素开始已经呈递增有序,编写一个算法把第1个元素删除且插入到链表中的适当位置.
请帮我看看,要一个完整的程序,直接可以上机调试的.谢谢...
#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);
static void DeleteInsert(LinkList *headPtr);
static void VisitList(LinkList headPtr);
static void DestroyList(LinkList *headPtr, LinkList *tailPtr);
int main(void)
{
LinkList headPtr = NULL, tailPtr = NULL;
CreateList(&headPtr, &tailPtr); /* 创建双向链表 */
VisitList(headPtr); /* 打印链表 */
if (headPtr != NULL) /* 链表不空的情况下 */
{
DeleteInsert(&headPtr); /* 删除第1元素后将其插入到适当位置 */
}
else
{
printf("list is empty.\n");
}
VisitList(headPtr); /* 打印链表 */
DestroyList(&headPtr, &tailPtr); /* 销毁链表 */
return 0;
}
static void CreateList(LinkList *headPtr, LinkList *tailPtr)
{
LinkList newPtr;
int i, n;
printf("Enter node number n: ");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
if ((newPtr = (LinkList)malloc(sizeof(Lnode))) == NULL)
{
exit(1);
}
scanf(" %c", &newPtr -> data);
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 DeleteInsert(LinkList *headPtr)
{
LinkList newPtr, pA, cA;
if ((newPtr = (LinkList)malloc(sizeof(Lnode))) == NULL)
{
exit(1);
}
newPtr -> data = (*headPtr) -> data;
newPtr -> priorPtr = NULL;
newPtr -> nextPtr = NULL;
*headPtr = (*headPtr) -> nextPtr;
for (pA = NULL, cA = *headPtr; cA != NULL; pA = cA, cA = cA -> nextPtr)
{
if (cA -> data > newPtr -> data)
{
pA -> nextPtr = newPtr;
newPtr -> priorPtr = pA;
newPtr -> nextPtr = cA;
cA -> priorPtr = newPtr;
break;
}
}
if (cA == NULL)
{
pA -> nextPtr = newPtr;
newPtr -> priorPtr = pA;
newPtr -> nextPtr = cA;
}
}
static void VisitList(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;
}
美女