有一个单向链表,链表中有可能出现“环”,就像下图这样。那么,如何用程序来判断该链表是否为有环链表呢?
方法1:
方法2:
分析:
代码:
package arithmetic.com.ty.binary; public class LinkedCycle { /** * 判断是否有环 * * @param head 链表头节点 */ public static boolean isCycle(Node head) { Node p1 = head; Node p2 = head; while (p2 != null && p2.next != null) { p1 = p1.next; p2 = p2.next.next; if (p1 == p2) { return true; } } return false; } /** * 链表节点 */ private static class Node { int data; Node next; Node(int data) { this.data = data; } } public static void main(String[] args) throws Exception { Node node1 = new Node(5); Node node2 = new Node(3); Node node3 = new Node(7); Node node4 = new Node(2); Node node5 = new Node(6); node1.next = node2; node2.next = node3; node3.next = node4; node4.next = node5; node5.next = node2; System.out.println(isCycle(node1)); } }
如果单向链表中存在环的情况,环长是多少?
/** * 计算环长 */ public static int cycleLenth(Node head) { Node p1 = head; Node p2 = head; int count = 0; int length = 0; while (count < 2 && p2 != null && p2.next != null) { if(count > 0) { length++; } p1 = p1.next; p2 = p2.next.next; if (p1 == p2) { count++; } } return length; }
原文:https://www.cnblogs.com/alimayun/p/12781501.html