首页 > 其他 > 详细

LeetCode -- Linked List cycle

时间:2015-11-21 07:07:51      阅读:161      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!