快慢指针解决单向链表是否有环的一系列问题
2017-10-15 19:56
323 查看
talk is cheap,show me the code......
证明参考:https://www.cnblogs.com/zhuzhenwei918/p/7491892.htmlpackage singleLinkedList;
/**
* @author Leon
* @date 创建时间:2017年10月15日 下午6:13:40
* @version 1.0
* 类说明 :
* 单向链表相关问题 例如:1 - 2 - 3 - 4 - 5 - 6 - 4 - .....
* 1、是否有环
* 2、环的长度
* 3、带环链表的实际长度
*/
public class Test
{
public static void main(String[] args)
{
Node n1 = new Node(1);
Node n2 = new Node(2);
Node n3 = new Node(3);
Node n4 = new Node(4);
Node n5 = new Node(5);
Node n6 = new Node(6);
n1.next = n2;
n2.next = n3;
n3.next = n4;
n4.next = n5;
n5.next = n6;
n6.next = n4;
System.out.println(isHoop(n1));
System.out.println(getLengthOfHoop(n1));
System.out.println(getLengthOfList(n1));
}
/*
* 对于问题1,使用追赶的方法,设定两个指针slow、fast,从头指针开始,每次分别前进1步、2步。
* 如存在环,则两者相遇;如不存在环,fast遇到NULL退出
*/
private static String isHoop(Node n1)
{
Node slow, fast;
slow = n1;
fast = n1;
while (fast != null)
{
fast = fast.next.next;
slow = slow.next;
if (fast == slow)
{
return "链表有环哦~";
}
}
return "链表没环哦~";
}
/*
* 对于问题2,记录下问题1的碰撞点p,slow、fast从该点开始,再次碰撞所走过的操作数就是环的长度s。
*/
private static String getLengthOfHoop(Node n1)
{
Node slow, fast, p = null;
slow = n1;
fast = n1;
while (fast != null)
{
fast = fast.next.next;
slow = slow.next;
if (fast == slow)
{
p = fast;
//System.out.println(p.value);
break;
}
}
if (p == null)
{
return "链表没环";
}
slow = p.next;
fast = p.next.next;
int operation = 1;
while (slow.value != fast.value)
{
s
4000
low = slow.next;
fast = fast.next.next;
operation++;
}
return "环的长度是:"+String.valueOf(operation);
}
/*
* 对于问题3,和前半部分加在一起就可以了。
*/
private static String getLengthOfList(Node n1)
{
Node slow, fast, p = null;
slow = n1;
fast = n1;
while (fast != null)
{
fast = fast.next.next;
slow = slow.next;
if (fast == slow)
{
p = fast;
//System.out.println(p.value);
break;
}
}
if (p == null)
{
return "链表没环";
}
slow=n1;
int result=0;
while(slow.value!=p.value)
{
result++;
slow=slow.next;
//System.out.println("hello");
}
//System.out.println(result);
//System.out.println(getLengthOfHoop(n1).charAt(getLengthOfHoop(n1).length()-1));
int resultT = result+Character.getNumericValue(getLengthOfHoop(n1).charAt(getLengthOfHoop(n1).length()-1));
//System.out.println(resultT);
return "链表长度:"+resultT;
}
}
class Node
{
public int value;
public Node next = null;
public Node(int value)
{
super();
this.value = value;
}
}
相关文章推荐
- 【链表】C++快慢两个指针解决问题(分别求倒数第k个、中间以及环的入口结点)
- PHP实现单向链表解决约瑟夫环问题
- C语言单向循环链表解决约瑟夫问题
- 关于指针的调用实现单向链表及指针函数的几个小问题
- 为什么用快慢指针检测链表是否有环的时候,快指针的步长选择的是2,而不是3,4,5?
- 算法学习笔记之四:巧妙运用指针解决链表、字符串、数组等问题(同向双指针VS对向双指针)
- “双指针”法解决链表问题
- 使用指针链表解决约瑟夫环问题
- flag4给出俩个单向链表的头指针,比如pA,pB,判断这俩个链表是否相交
- 判断链表是否有环为什么快慢指针一定会相遇
- <仅是自己做笔记。。。系列-6>判断俩个链表是否相交 给出俩个单向链表的头指针,比如h1,h2,判断这俩个链表是否相交。
- 用快慢指针判断单链表环,找到环入口 扩展到判断两个链表是否相交
- 解决Hsqldb指针只能单向移动,不能回滚问题(.first())
- 链表面试题之快慢指针问题(一) 查找链表中间节点
- 单链表是否有环的问题解决与讨论(java实现)
- 第7题 微软亚院之编程判断俩个链表是否相交 给出俩个单向链表的头指针,比如h1,h2,判断这俩个链表是否相交,并找出第一个相交结点。
- C语言单向循环链表解决约瑟夫问题
- 用单向循环链表解决约瑟夫环(Joseph)问题
- 利用单向环链表解决约瑟夫问题
- [转]用单向循环链表解决约瑟夫环问题