单链表是否有环,环的大小,第一个连接点,有环的单链表长度
2016-04-24 20:06
176 查看
给定一个单链表,只给出头指针h:
1、如何判断是否存在环?
2、如何知道环的长度?
3、如何找出环的连接点在哪里?
4、带环链表的长度是多少?
下面是实现,可以相互检查一下是否不正确。
1、如何判断是否存在环?
2、如何知道环的长度?
3、如何找出环的连接点在哪里?
4、带环链表的长度是多少?
下面是实现,可以相互检查一下是否不正确。
/* 2 Here we discuss four question about single list 3 1. isCircle(ListNode* head) 4 2. lenghtOfCircle_list(ListNode* head) 5 3. firstNodeOfCircle(ListNode* head) 6 4. lengthOfCircle(ListNode* head); 7 */ 8 struct ListNode{ 9 int val; 10 ListNode* next; 11 }; 12 bool isCircle(ListNode* head){ 13 14 if(head==NULL) 15 return false; 16 ListNode* slow=head; 17 ListNode* fast=head; 18 while(fast!=NULL){ 19 slow=slow->next; 20 if(fast->next!=NULL) 21 fast = fast->next->next; 22 if(slow==fast) 23 return true; 24 } 25 return false; 26 } 27 int lengthOfCircle(ListNode* head){ 28 if(head==NULL) 29 return 0; 30 int result=0; 31 ListNode* slow=head; 32 ListNode* fast=head; 33 while(fast!=NULL){ 34 slow=slow->next; 35 if(fast->next!=NULL) 36 fast = fast->next->next; 37 if(slow==fast){ 38 //conflict node, 39 result++; 40 slow=slow->next; 41 fast=fast->next->next; 42 while(slow!=fast){ 43 slow=slow->next; 44 fast=fast->next->next; 45 result++; 46 } 47 return result; 48 } 49 } 50 return result; 51 } 52 ListNode* firstNodeOfCircle(ListNode* head){ 53 if(head==NULL) 54 return 0; 55 int result=0; 56 ListNode* slow=head; 57 ListNode* fast=head; 58 while(fast!=NULL){ 59 slow=slow->next; 60 if(fast->next!=NULL) 61 fast = fast->next->next; 62 if(slow==fast){ 63 //conflict node, 64 while(slow!=head){ 65 slow=slow->next; 66 head=head->next; 67 } 68 return head; 69 } 70 } 71 return NULL; 72 73 } 74 int lenghtOfCircle_list(ListNode* head){ 75 if(head==NULL) 76 return 0; 77 int result=lengthOfCircle(head); 78 if(result==0){ 79 //no circle 80 ListNode* node=head; 81 int res=0; 82 while(node!=NULL){ 83 node=node->next; 84 ++res; 85 } 86 return res; 87 } 88 ListNode* temp=firstNodeOfCircle(head); 89 ListNode* node=head; 90 int res=0; 91 while(temp!=node){ 92 res++; 93 node = node->next; 94 } 95 return res+lengthOfCircle(head); 96 }
相关文章推荐
- Noip2004普及组
- 云计算技术
- 基于人机交互设计对搜狗输入法的评价
- LeetCode 104. Maximum Depth of Binary Tree C语言
- 百度百科爬虫
- ssh批量登录机器并返回命令的执行结果
- Access数据库从入门到进门——基础操作篇
- 《构建之法》阅读笔记04
- 【二分】XMU 1587 中位数
- 剑指offer:二叉搜索树的后序遍历序列
- 配合LLDB调试器进行iOS代码调试
- 实验一Java开发环境的熟悉
- vs无法打开模块文件
- java中遍历MAP的几种方法
- HDFS的读写限流方案
- 《CSS3实战》笔记--弹性盒模型(三)
- css3的box-sizing
- Unity常用脚本类的继承关系
- [剑指offer]数值的整数次方
- frontpage 2010.2003绿色版