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

Linked List Cycle II

时间:2014-07-01 11:30:58      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:java   leetcode   

题目

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

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

方法

    public ListNode detectCycle(ListNode head) {
    	if (head == null || head.next == null) {
    		return null;
    	}
    	ListNode first = head;
    	ListNode second = head;
    	while (second != null) {
    		second = second.next;
    		if (second != null) {
    			second = second.next;
    		} else {
    			return null;
    		}
    		first = first.next;
    		if (second == first) {
    			break;
    		}
    	}
    	if (second == null) {
    		return null;
    	} else {
    		ListNode node = head;
    		while(second != node){
    			second = second.next;
    			node = node.next;
    		}
    		return node;
    	}
    	
    }


Linked List Cycle II,布布扣,bubuko.com

Linked List Cycle II

标签:java   leetcode   

原文地址:http://blog.csdn.net/u010378705/article/details/36025647

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