LeetCode -- Linked List Cycle II

原创 2015年11月21日 10:13:18
题目描述:


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?




判断链表是否有环,如果存在,返回环起始节点;如果不存在,返回Null。


思路:
1. 使用快慢指针的方法找到环的位置。
2. 如果找到了环,慢指针回到起点,快慢指针每次各走一步,下一次相遇的位置就是环的起点。




实现代码:


/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode DetectCycle(ListNode head) 
    {
        if(head == null){
    		return null;
    	}


        var p = head;
    	var q = head;
    	
    	var found = false;
    	while(p != null && q != null && q.next != null && !found){
    		var t = q;
    		p = p.next;
    		q = q.next.next;
    		if(ReferenceEquals(p,q)){
    			found = true;
    		}
    	}
    	
        if(!found){
    		return null;
    	}
    	
    	// p start from head again
    	// and q standing where it is
    	// next time they meet point is where cycle starts from
    	p = head;
    	while(!ReferenceEquals(p, q)){
    		p = p.next;
    		q = q.next;
    	}
    	
    	return q;
    }
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

【LeetCode】Linked List Cycle II

参考链接 http://www.cnblogs.com/x1957/p/3406448.html 题目描述 Linked List Cycle II   Give...

leetcode:Linked List Cycle II

COPY FROM: 比I麻烦点的就是找到循环开始点TAT I只是判断是否循环。要求不使用额外空间(不然hash就可以了 按I的思路,我们又慢指针S和快指针F。。。F走两...

【LeetCode】Linked List Cycle II

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

[leetcode] 142. Linked List Cycle II

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

LeetCode 142 Linked List Cycle II

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

[leetcode] 142. Linked List Cycle II 解题报告

题目链接:https://leetcode.com/problems/linked-list-cycle-ii/ Given a linked list, return the node wher...

[LeetCode] Linked List Cycle II, Solution

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

【LeetCode】linked-list-cycle-ii

题干Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull. Fo...

[leetcode] 142.Linked List Cycle II

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

[LeetCode] 142. Linked List Cycle II java

/**142. Linked List Cycle II * @param head * @return */ public ListNode detectCy...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:LeetCode -- Linked List Cycle II
举报原因:
原因补充:

(最多只允许输入30个字)