快慢指针解决单向链表是否有环的一系列问题

来源:互联网 发布:淘宝积分 编辑:程序博客网 时间:2024/05/23 21:58

talk is cheap,show me the code......

package 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){slow = 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;}}