单循环链表的实现(C语言版)

注:代码注释及说明待补充……

   结构声明

typedef int elem_type; struct LNode { elem_type elem; LNode * next; }; typedef LNode * circ_list;

 基本操作

status_code init_list( circ_list & lst ) { lst = (circ_list)malloc( sizeof( LNode ) ); lst->elem = -1; lst->next = lst; return Success; } status_code clear_list( circ_list & lst ) { lst = lst->next; LNode * p = lst->next; while( p != lst ) { lst->next = p->next; free( p ); p = lst->next; } return Success; } status_code free_list( circ_list & lst ) { if( lst == NULL ) return status_code::Failure; lst = lst->next; LNode * p = lst->next; while( p != lst ) { lst->next = p->next; free( p ); p = lst->next; } free( lst ); lst = NULL; return Success; } bool list_empty( const circ_list & lst ) { return lst->next == lst; } int list_size( const circ_list & lst ) { int len = 0; LNode * q = lst->next, * p = q->next; while( p != q ) { ++len; p = p->next; } return len; } status_code list_insert( circ_list & lst, int i, const elem_type & e ) { status_code res = Success; int j = 0; LNode * h = lst->next, * p = h; while( p->next != h && j < i - 1 ) { ++j; p = p->next; } if( ( p->next == h && j < i - 1 ) || j > i - 1 ) { res = RangeError; } else { LNode * s = ( LNode * )malloc( sizeof( LNode ) ); s->elem = e; s->next = p->next; p->next = s; if( s->next == h ) lst = s; } return res; } status_code list_delete( circ_list & lst , int i, const elem_type & e ) { status_code res = Success; LNode * h = lst->next, * p = h; int j = 0; while( p->next != h && j < i - 1 ) { ++j; p = p->next; } LNode * pp = p->next; if( j > i - 1 || ( p->next == h && j <= i - 1 ) ) { res = RangeError; } else { LNode * q = p->next; p->next = q->next; if( lst == q ) lst = p; free( q ); } return res; } void list_traverse( const circ_list & lst ) { if( lst->next == lst ) { printf( "The list is empty!/n" ); return; } LNode * h = lst->next, * p = h->next; while( p != h ) { printf( "%3d ", p->elem ); p = p->next; } printf( "/n" ); }

你可能感兴趣的:(单循环链表的实现(C语言版))