C++编程语言是一款应用广泛的计算机应用语言。我们在这篇文章中为大家介绍的是关于C++单向链表的实现方法。希望初学者们可以通过本文介绍的内容充分掌握这方面的知识,并从中体验到这款语言功能的强大。

C++单向链表实现代码:
- #include < iostream>
 - using namespace std;
 - template < class T>
 - struct node
 - {
 - //public:
 - // 结构体成员默认就是public的
 - T data;
 - node< T> *next;
 - };
 - //typedef struct node NODE;
 - //typedef NODE *NODEPTR;
 - //typedef后面要跟具体的类类型,而不是一个类模版。eg: typedef node< T>
 
NODE (C++中,实例化结构体时struct可省略)- template < class T>
 - class list
 - {
 - public:
 - //以下三个函数要供外部调用,所以要声明为public,class默认为private。
 - /*
 - void creat(T &p);
 - void print(T p);
 - void destroy(T &p);
 - */
 - //这三个函数的参数有问题,按照下文的实现,我认为应改为如下:
 - void creat(T *p);
 - void print(T *p);
 - void destroy(T *p);
 - };
 - template< class A>
 - //void creat(A &p)
 - void list< A>::creat(A *p)
 - {
 - //class node *q;
 - //形参里的A就是这个程序的node类型
 - char ch = 0; //下数第4行cin>>ch 中的ch未定义,在此补充
 - A *q = NULL;
 - q=p; //必须新增这一句,q用于以后的动态分配
 - cout< < "input"< < endl;
 - cin>>ch;
 - // if(!p) //这个if放在while里会影响效率,故移到while外边,
 
改过程序之后,实际上用不着了- // {
 - //p=new struct node;
 - //语法错误,形参里的A就是这个程序的node类型
 - // p = new A();
 - if(ch!='#')
 - p->data=ch;
 - // }
 - cin>>ch;
 - while(ch!='#')
 - {
 - //q->next=new class node;
 - //语法错误,形参里的A就是这个程序的node类型
 - q->next = new A();
 - //q->next=ch;
 - //这句应该是给data赋值
 - q->next->data = ch;
 - qq = q->next; //必须新增这一句,q用于以后的动态分配
 - cin>>ch;
 - }
 - q->next=NULL;
 - }
 - template < class T>
 - void list< T>::print(T *p)
 - {
 - if(p)
 - {
 - cout< < p->data< < " ";
 - print(p->next);
 - }
 - }
 - template < class T>
 - void list< T>::destroy(T *p)
 - {
 - if(p)
 - {
 - destroy(p->next);
 - delete p->next;
 - }
 - }
 - int main()
 - {
 - // NODEPTR p;
 - node< int> p;
 - // list L; 模版要有参数
 - list< node< int> > L;
 - L.creat(&p);
 - cout < < endl < < endl < < "show:" < < endl;
 - L.print(&p);
 - L.destroy(&p);
 - return 0;
 - }
 
实现C++单向链表时,程序使用了指针,如果改用引用更好些。
【编辑推荐】
                网站栏目:C++单向链表实现代码解读
                
                新闻来源:http://www.csdahua.cn/qtweb/news43/357143.html
            
成都网站优化推广公司_创新互联,为您提供静态网站、网站营销、企业建站、网站制作、品牌网站建设、服务器托管
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 快上网