首页 > 其他 > 详细

Linked List Cycle II

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

题目

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!