如何用C++递归的方法来将循环链表的unique data找出来
2017-10-25 11:34
561 查看
这道题目是小编考期中的题目,当时再做的时候,尽然忘记了一个条件,最后跑出无限循环。哎!可惜了。
不说了,直接上代码:
下面是实现这几个函数代码展示:
下面是结果的展示:
不说了,直接上代码:
//This is the list.h file #include<iostream> #include<cctype> #include<cstring> using namepace std; struct node { int data; node * next; }; class list { public: //These functions are provided list(); //Supplied ~list(); //Supplied void build(); //Supplied void display(); //Supplied //Display the unique data in the CLL //Return number of unique data int count_unique(); private: //Display the unique data in the CLL //Return number of unique data int count_unique(node * rear, node * head); int compare(node * head, int num); node * rear; };
下面是实现这几个函数代码展示:
//This is the clist.cpp #include "clist.h" int list::count_unique() { return count_unique(rear,rear->next); } int list::count_unique(node * rear, node * head) { if(!head || !rear) return 0; if(head != rear) { if(compare(rear->next,head->data) == 1) { cout<<head->data<<" "; return count_unique(rear,head->next) + 1; } else { return count_unique(rear,head->next); } } else { if(compare(rear->next,head->data) == 1) { cout<<head->data<<" "; return 1; } else return 0; } } //因为这个是循环链表 //所以在找unique的时候,就得考虑到如何防止无限循环 int list::count_unique(node * head, int num) { if(!head) return 0; if(head != rear) { if(head->data == num) return compare(head->next,num) + 1; else return compare(head->next,num); } else { if(head->data == num) return 1; else return 0; } }
下面是结果的展示:
相关文章推荐
- 如何用C++来实现在循环链表里展示除了最后一个节点,然后返回所展示的节点总和
- 如何判断一个单向链表是否存在循环的经典方法
- 如何用C++实现双向循环链表
- C/C++用递归的方法求链表逆序
- C++循环链表之约瑟夫环的实现方法
- C++ 链表的递归逆转和循环逆转
- 用C++实现单向循环链表的解决方法
- 反转一个链表的两种方法:递归和循环
- 队列(queue)的链表(list)实现及循环数组(circular array)实现 C++实现
- 单向链表判断是否存在循环的经典方法
- 在循环中读取sqlDataReader.Read()中的所有列,数据类型如何转换?
- 双向循环链表的c++模板类
- 如何防止覆盖(override)toString方法时产生递归调用
- 如何防止覆盖(override)toString方法时产生递归调用
- 关于C++中如何判断文件,目录存在的若干方法
- JAVA如何调用C/C++方法
- 如何编写从M中选N的组合数程序,一个不用递归方法设计,一个用递归方法设计
- 在 C/C++中如何构造通用的对象链表
- 如何防止重载toString方法时产生递归调用
- 如何防止覆盖(override)toString方法时产生递归调用