检查单链表中是否有环

来源:互联网 发布:龙应台安德烈现状知乎 编辑:程序博客网 时间:2024/06/11 09:10

单链表判断是否有环


判断原理

用两个指针,从头节点开始遍历,一个指针a每次走1步,一个指针b每次都2步。

如果有环,两个指针相遇前

  1. b位于a后一位时,那么a,b指针下次相遇。
  2. b位于a后两位时,那么a,b指针下下次即将相遇。

算法实现

创建链表

public static Node createList(int max) {boolean setCycle = setCycle();System.out.println("createList " + max + "  hasCycle=" + setCycle);Node firstNode = new Node();firstNode.data = 0;Node curNode = firstNode;for(int i = 1; i <= max; i ++) {Node node = new Node();node.data = i;curNode.next = node;curNode = node;if (setCycle && (i == max)) {curNode.next = firstNode;}}return firstNode;}public static boolean setCycle() {Random random = new Random();int data = random.nextInt(10);if (data > 3) {return true;}return false;}

判断有无环

public static boolean isCycle(Node firstNode) {if (firstNode == null) {return false;}if (firstNode.next == null) {return false;}boolean firstTime = true;Node curNode1 = firstNode;Node curNode2 = firstNode;while(curNode2 != null) {if (curNode1 == curNode2 && !firstTime) {return true;}firstTime = false;curNode1 = curNode1.next;curNode2 = curNode2.next;if (curNode2 == null) {continue;}curNode2 = curNode2.next;}return false;}

main方法

public static void main(String[] args) {for(int i = 0; i < 9; i ++) {int max = newMax();Node node = createList(max);boolean isC = isCycle(node);System.out.println(" check isC = " + isC);System.out.println("---------------------------");}}

打印结果


0 0
原创粉丝点击