对于有头结点的双链表L,当L为空时,L->pre == L && L->next == L;
对循环双链表的插入操作,需要考虑到链表为空的特殊情况;
对循环上链表的删除操作,需要考虑到被删除元素为链表中最后一个元素的特殊情况。
具体代码如下:
#include<stdlib.h>
#include<iostream>
struct List{
int val;
List* pre;
List* next;
};
List* initList( List **L ) //make an empty List
{
*L = ( List* )malloc( sizeof( struct List ) );
(*L)->next = *L; //this is very important
(*L)->pre = *L;
return *L;
}
bool isEmpty( List* L) //test the list is an empty list or not
{
return ( L->next == L && L->pre == L );
}
void insert( List* L, int x )
{
List* tmp = ( List* )malloc( sizeof( struct List ) );
if( tmp == NULL )
std::cerr << "MEMORY OUT!" << std::endl;
tmp->val = x;
if( isEmpty( L ) ) //the list is empty before insert the element x
{
tmp->next = L->next;
tmp->pre = L;
L->next = tmp;
L->pre = tmp;
}
else // the list is not empty
{
tmp->next = L->next;
tmp->next->pre = tmp;
tmp->pre = L;
L->next = tmp;
}
}
List* findPos( List* L, int x ) //find element x in List L, return the priori list node
{
List* position;
List* tmp = L->next;
if( L->next == L )//empty list
return position;
while( tmp != L && tmp->val != x )
tmp = tmp->next;
if( tmp->val == x)
position = tmp;
return position;
}
void deleteElem( List* L, int x ) //delete element x in List
{
List* tmp;
List* position = findPos( L, x );
if( position == L )
std::cerr << "No Elem!" << std::endl;
else
{
if( position->next == L ) //find the elem in the last node
{
position->pre->next = L;
L->pre = position->pre;
free( position );
}
else //find the element in the middle of List
{
position->next->pre = position->pre;
position->pre->next = position->next;
free( position );
}
}
}
void deleteList( List *L ) //delete the whole List
{
List *tmp;
while( L->next != L )
{
tmp = L->next;
L->next->pre = L;
L->next = L->next->next;
free( tmp );
}
}
void outputList( List* L ) //output the list
{
List* tmp = L;
while( tmp->next != L )
{
std::cout << tmp->next->val << " ";
tmp = tmp->next;
}
std::cout << std::endl;
}
int main( int _argc, char **__argv)
{
int arrcnt = 10;
int arr[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
List* L;
initList( &L );
for( int i = 0; i < arrcnt; ++i )
insert( L, arr[i] );
outputList( L );
//List* pos = findPri( L, 5);
//std::cout << pos->val << std::endl;
deleteElem( L, 6 );
outputList( L );
deleteList( L );
std::cin.get();
return 0;
}