C++实现的链表类实例

这篇文章主要介绍了C++实现的链表类,以完整实例分析了C++实现链表类的定义、插入、删除、遍历、统计等相关技巧,需要的朋友可以参考下

本文实例讲述了C++实现的链表类。分享给大家供大家参考。具体如下:

 #include  using namespace std; class linklist { private: struct node { int data; node *link; }*p; public: linklist(); void append( int num ); void add_as_first( int num ); void addafter( int c, int num ); void del( int num ); void display(); int count(); ~linklist(); }; linklist::linklist() { p=NULL; } void linklist::append(int num) { node *q,*t; if( p == NULL ) { p = new node; p->data = num; p->link = NULL; } else { q = p; while( q->link != NULL ) q = q->link; t = new node; t->data = num; t->link = NULL; q->link = t; } } void linklist::add_as_first(int num) { node *q; q = new node; q->data = num; q->link = p; p = q; } void linklist::addafter( int c, int num) { node *q,*t; int i; for(i=0,q=p;ilink; if( q == NULL ) { cout<<"\nThere are less than "<data = num; t->link = q->link; q->link = t; } void linklist::del( int num ) { node *q,*r; q = p; if( q->data == num ) { p = q->link; delete q; return; } r = q; while( q!=NULL ) { if( q->data == num ) { r->link = q->link; delete q; return; } r = q; q = q->link; } cout<<"\nElement "<link ) cout<data; } int linklist::count() { node *q; int c=0; for( q=p ; q != NULL ; q = q->link ) c++; return c; } linklist::~linklist() { node *q; if( p == NULL ) return; while( p != NULL ) { q = p->link; delete p; p = q; } } int main() { linklist ll; cout<<"No. of elements = "<赞(0) 打赏
未经允许不得转载:0133技术站首页 » C语言