码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode -- Linked List cycle

时间:2015-11-21 07:08:45      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:

本题描述:


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


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


检测链表中是否有环。


思路:
经典算法,使用快慢指针,快的一次走两步,慢的一次走一步,如果有环它们一定会相遇。


实现代码:




/**
 * 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 bool HasCycle(ListNode head) {
        if(head == null){
    		return false;
    	}
    	
    	var p = head;
    	var q = head;


    	while(p != null && q != null && q.next != null){
    		var t = q;
    		p = p.next;
    		q = q.next.next;
    		if(ReferenceEquals(p,q)){
    			return true;
    		}
    	}
    	return false;
    }
}


LeetCode -- Linked List cycle

标签:

原文地址:http://blog.csdn.net/lan_liang/article/details/49947067

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!