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

[LeetCode]Linked List Cycle

时间:2014-07-03 18:42:10      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:blog   java   使用   2014   for   算法   

题目:给定一个单链表,判断链表是否存在环路(能否不使用额外内存空间)

算法:快慢指针

原理:每次,快指针走一步,慢指针走两步,若链表存在循环,则快慢指针最终必定会在某个节点汇合,否则直到遍历完整个链表都不会汇合

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public boolean hasCycle(ListNode head) {
	    	if (null==head || null==head.next) {
	    		return false;
	    	}
	    	
	    	ListNode fast = head;  // fast pointer take one step
	    	ListNode slow = head.next.next;  // slow pointer take two steps
	    	while (null!=fast && null!=slow) {
	    		if (fast == slow) {
	    			// fast pointer meet slow pointer, it means list has cycle!
	    			return true;
	    		}
	    		
	    		if (null == slow.next) {
	    			// it mean slow pointer has reach the list tail! No cycle!
	    			return false;
	    		}
	    		else {
	    			fast = fast.next;
		    		slow = slow.next.next;
	    		}
	    	}
	    	return false;
	    }
}


[LeetCode]Linked List Cycle,布布扣,bubuko.com

[LeetCode]Linked List Cycle

标签:blog   java   使用   2014   for   算法   

原文地址:http://blog.csdn.net/yeweiouyang/article/details/36418519

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