【leetcode】Linked List Cycle

问题描述:

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space? 


思路:

1.遍历链表,比较set中是否包含节点的地址,如果包含说明是有环,如果不包含,则将地址存入到set中;

缺点:leetcdoe显示time limited

	//time limited..
	public boolean hasCycle1(ListNode head) {
		if(head==null)
			return false;
		Set<String> address = new HashSet<String>();
		while(head.next!=null){
			System.out.println(head.toString());
			if(address.contains(head.toString()))
				break;
			address.add(head.toString());
			head=head.next;
		}
		if(head.next==null)
			return false;	
        return true;
    }

2.快慢指针:我很喜欢一个比喻,有两个人同时绕着操场跑,一个速度是另一个速度的两倍,这样以来两人肯定回碰到一起;快慢指针也是同理,在遍历时,让一个节点的后向遍历速度为next;另一个为next.next;如果有重复,两个指针肯定回碰到;

public boolean hasCycle(ListNode head) {
		boolean result = false;
		if(head==null)
			return false;
		ListNode flagA = head;
		ListNode flagB = head;
		while(flagB.next!=null&&flagB.next.next!=null){
			flagA=flagA.next;
			flagB=flagB.next.next;
			if(flagA==flagB){
				result = true;
				break;
			}
		}
        return result;
    }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值