链表的实现以及链表中的常用操作
代码如下:
#include<stdlib.h>
#include<iostream>
struct List{
int val;
List *next;
};
List* initList( List **L )//make an empty List
{
*L = ( List* )malloc( sizeof( struct List ) );
(*L)->next = NULL; //this is very important
return *L;
}
bool isEmpty( List* L)//test the list is an empty list or not
{
return L->next == NULL;
}
void insert( List* L, int x )//insert an elem
{
List* tmp = ( List* )malloc( sizeof( struct List ) );
if( tmp == NULL )
std::cerr << "MEMORY OUT!" << std::endl;
tmp->val = x;
tmp->next = L->next;
L->next = tmp;
}
List* findPri( List* L, int x )//find element x in List L, return the previous list node
{
List* position;
List* tmp = L;
if( L->next == NULL )
return position;
while( tmp->next != NULL && tmp->next->val != x )
tmp = tmp->next;
if( tmp->next->val == x)
position = tmp;
return position;
}
List* findPos( List* L, int x )//find element x in List L
{
List* pos = findPri( L, x );
if( pos != NULL )
return pos->next;
else
return NULL;
}
void deleteElem( List* L, int x ) //Delete elem x in List L,if not found, output error
{
List* tmp;
List* position = findPri( L, x );
if( position == NULL )
std::cerr << "No Elem!" << std::endl;
else
{
tmp = position->next;
position->next = tmp->next;
free( tmp );
}
}
void deleteList( List *L )//delete whole List
{
List *tmp;
while( L->next != NULL )
{
tmp = L->next;
L->next = L->next->next;
free( tmp );
}
}
void outputList( List* L )// output the whole List
{
List* tmp = L;
while( tmp->next != NULL )
{
std::cout << tmp->next->val << " ";
tmp = tmp->next;
}
std::cout << std::endl;
}
int main( int _argc, char **__argv)//Main function
{
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, 5 );
outputList( L );
deleteList( L );
std::cin.get();
return 0;
}