LeetCode-141.142. Linked List Cycle (JAVA)链表找环

141. 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?

链表是否存在环

Set解法

	public boolean hasCycle(ListNode head) {
		Set<ListNode> set = new HashSet<>();
		while (head != null) {
			if (!set.add(head))
				return true;
			head = head.next;
		}
		return false;
	}

快慢指针:

	public boolean hasCycle(ListNode head) {
		ListNode fast = head;
		ListNode slow = head;
		while (fast != null && fast.next != null) {
			fast = fast.next.next;
			slow = slow.next;
			if(fast==slow)
				return true;
		}

		return false;
	}

142. Linked List Cycle II

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Note: Do not modify the linked list.

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

Set解法

	public ListNode detectCycle(ListNode head) {
		Set<ListNode> set = new HashSet<>();
		while (head != null) {
			if (!set.add(head))
				return head;
			head = head.next;
		}
		return null;
	}

快慢指针

感谢:http://www.jianshu.com/p/ce7f035daf74 解析


142.LinkedListCycleII

图中,

  • X是链表的起点。
  • Y是环的起点。
  • Zfastslow首次相遇的地方(二者同时从X出发,slow每次移动一步,fast每次移动两步)。
  • a, b, c分别表示XY(蓝色), YZ(红色), ZY(绿色)的长度。

fastslowZ点首次相遇时:

  • fast移动的距离是:a + b + c + b
  • slow移动的距离是:a + b

因为fast的移动速度是slow的两倍,所以:

(a + b + c + d) == 2 * (a + b)

由此可以推出:

a == c

我们需要用上面的推论来寻找环的起点(Y)。

fastslow首次相遇时,我们就到了Z点。

由于a == c,也就是XYZY的距离相等。

因此,如果我们让指针pq分别从XZ出发,并且每次都移动一步,当它们相遇时,恰好就是环的起点Y

	public ListNode detectCycle(ListNode head) {
		ListNode fast = head;
		ListNode slow = head;
		while (fast != null && fast.next != null) {
			fast = fast.next.next;
			slow = slow.next;
			if (fast == slow) {
				fast = head;
				while (fast != slow) {
					fast = fast.next;
					slow = slow.next;
				}
				return slow;
			}
		}

		return null;

	}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值