<span style="font-size:18px;">
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
typedef int ItemValue;
const int sleep_time = 10000;
typedef struct DoubleLinkedList
{
ItemValue value;
struct DoubleLinkedList *pre;
struct DoubleLinkedList *next;
} DoubleList, *pDoubleList;
DoubleList *CreateCylicDoubleLinkedList()
{
printf("创建循环双链表!\n");
DoubleList *head = (DoubleList *)malloc(sizeof(DoubleList));
head->pre = head;
head->next = head;
DoubleList *pTemp;
pTemp = head;
ItemValue iValue;
while (scanf("%d", &iValue) != EOF)
{
DoubleList *p = (DoubleList *)malloc(sizeof(DoubleList));
p->value = iValue;
p->pre = pTemp;
p->next = head;
pTemp->next = p;
pTemp = p;
head->pre = p;
}
return head;
}
#if 0
/* 访问循环双链表 */
void VisitCylicDoubleLinkedList(DoubleList *dl)
{
printf("循环双链表的输出!\n");
DoubleList *pTemp;
pTemp = dl;
while (pTemp->next != dl)
{
printf("%d ", pTemp->next->value);
pTemp = pTemp->next;
}
}
#endif
#if 1
/* 访问循环双链表 */
void VisitCylicDoubleLinkedList(DoubleList *dl)
{
printf("循环双链表的输出!\n");
DoubleList *pTemp;
pTemp = dl;
pTemp = pTemp->next;
while (pTemp != dl)
{
printf("%d ", pTemp->value);
pTemp = pTemp->next;
}
}
#endif
/* 删除元素 */
void DeleteCylicDoubleLinkedList(DoubleList *L, int pos)
{
printf("\n删除位置为%d上的元素\n", pos);
if (L == NULL) {
printf("链表为空!\n");
Sleep(sleep_time);
exit(1);
}
if (pos <= 0) {
printf("\n删除位置不合理! 必须从第1个结点开始\n");
Sleep(sleep_time);
exit(1);
}
DoubleList *pTemp;
pTemp = L;
pTemp = pTemp->next;
int i=1;
while (pTemp != L && i!=pos)
{
pTemp = pTemp->next;
i++;
}
if (pTemp == L) {
printf("\n删除结点不在链表中!\n");
Sleep(1000);
exit(1);
}
else
{
pTemp->next->pre = pTemp->pre;
pTemp->pre->next = pTemp->next;
}
}
/* 在位置i之后插入元素value */
void InsertItemInDoubleLinkedList(DoubleList *L, ItemValue iValue, int pos)
{
if (L == NULL)
{
printf("\n插入链表为空! \n");
}
if (pos <= 0)
{
printf("\n插入位置不合理! \n");
Sleep(sleep_time);
exit(1);
}
DoubleList *pInsert = (DoubleList *)malloc(sizeof(DoubleList));
pInsert->value = iValue;
DoubleList *pTemp;
pTemp = L;
int i = 0; //插入元素前一个结点标号
while (pTemp->next != L && i != pos-1)
{
pTemp = pTemp->next;
i++;
}
if (pTemp->next != L && i==pos-1)
{
pInsert->next = pTemp->next;
pTemp->next->pre = pInsert;
pInsert->pre = pTemp;
pTemp->next = pInsert;
return;
}
if (pTemp->next == L && i==pos-1)
{
pInsert->next = pTemp->next;
pInsert->pre = pTemp;
L->pre = pInsert;
pTemp->next = pInsert;
}
else
{
printf("\n插入位置超出链表!\n");
Sleep(sleep_time);
exit(1);
}
}
int main()
{
DoubleList *DL;
DL = CreateCylicDoubleLinkedList();
VisitCylicDoubleLinkedList(DL);
DeleteCylicDoubleLinkedList(DL, 5);
VisitCylicDoubleLinkedList(DL);
InsertItemInDoubleLinkedList(DL, 100, 4);
VisitCylicDoubleLinkedList(DL);
free(DL);
system("pause");
return 0;
}
</span>
其中循环双链表的插入操作,不简练,还没想到简洁方法,能够实现:首结点、中部结点、尾部结点插入操作