检查单链表中是否有环

单链表判断是否有环


判断原理

用两个指针,从头节点开始遍历,一个指针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("---------------------------");
		}

	}

打印结果


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值