缘由
本人C++菜鸟一枚,打算一边复习数据结构、算法,一边学习C++。That’s All!
下面是C++链表的一个简单实现。
/*链表的增删改查*/ #include <iostream> #include <string.h> using namespace std; #define LEN (16) #define BUF (1024) class node { public: char value[BUF]; node *next; }; class node_op { public: node *node_init( const char *value ) { node *q = new node; strncpy( q->value, value, strlen( value ) ); q->next = NULL; return q; } void node_free( node *q ) { delete q; } }; class list_op:public node_op { public: void list_init( node *list ) { memset( list->value, 0, BUF ); list->next = NULL; } void list_add( node *list, node *q, int p ) { if ( !p ) { p = 1; //默认首部增加 } if ( list->value[0] + 1 < p ) { cout << "error: illegal position,current len is " << ( int )list->value[0] << endl; return; } list->value[0] ++; while ( --p ) { list = list->next; } q->next = list->next; list->next = q; } void list_del( node *list, int p ) { if ( !p ) { p = 1; } if ( list->value[0] < p ) { cout << "error: illegal position,current len is " << ( int )list->value[0] << endl; return; } list->value[0] --; while ( --p ) { list = list->next; } node *q = list->next; list->next = q->next; node_op op; op.node_free( q ); } void list_modify( node *list, const char *value, int p ) { if ( !p ) { p = 1; } if ( list->value[0] < p ) { cout << "error: illegal position,current len is " << ( int )list->value[0] << endl; return; } while ( p-- ) { list = list->next; } memset( list->value, 0, strlen( list->value ) ); strncpy( list->value, value, strlen( value ) ); } void list_show( node *list, int p ) { if ( !p ) { p = 1; } if ( list->value[0] < p ) { cout << "error: illegal position,current len is " << ( int )list->value[0] << endl; return; } while ( p-- ) { list = list->next ; } cout << "value is " << list->value << endl; } }; int main() { node *list; list = new node; list_op op; op.list_init( list ); //node *head = list; node *q = op.node_init( "test" ); op.list_add( list, q, 1 ); cout << "node:" << list->next->value << endl; node *p = op.node_init( "test2" ); op.list_add( list, p, 2 ); cout << "node:" << list->next->next->value << endl; node *r = op.node_init( "test4" ); op.list_add( list, r, 2 ); cout << "node:" << list->next->next->value << endl; op.list_del( list, 1 ); cout << "node:" << list->next->value << endl; op.list_modify( list, "test1", 1 ); cout << "node:" << list->next->value << endl; int i = ( int )list->value[0]; while ( i ) { op.list_show( list, i ); i--; } delete list; return 0; }