程序员面试金典-面试题 02.08. 环路检测

题目:

给定一个有环链表,实现一个算法返回环路的开头节点。
有环链表的定义:在链表中某个节点的next元素指向在它前面出现过的节点,则表明该链表存在环路。


示例 1:

输入:head = [3,2,0,-4], pos = 1
输出:tail connects to node index 1
解释:链表中有一个环,其尾部连接到第二个节点。

示例 2:

输入:head = [1,2], pos = 0
输出:tail connects to node index 0
解释:链表中有一个环,其尾部连接到第一个节点。

示例 3:

输入:head = [1], pos = -1
输出:no cycle
解释:链表中没有环。

进阶:
你是否可以不用额外空间解决此题?

分析:

快慢指针,快指针一次走两个元素,慢指针一次走一个元素,如果链表存在环的话,快慢指针一定会相遇,且从相遇节点,和头节点到达环的起始节点的距离是相同的。

程序:

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode detectCycle(ListNode head) {
        ListNode fast = head;
        ListNode slow = head;
        while(fast != null && fast.next != null){
            fast = fast.next.next;
            slow = slow.next;
            if(slow == fast)
                break;
        }
        if(fast == null || fast.next == null)
            return null;
        fast = head;
        while(slow != null && fast != null){
            if(slow == fast)
                break;
            slow = slow.next;
            fast = fast.next;
        }
        return fast;
    }
}

猜你喜欢

转载自www.cnblogs.com/silentteller/p/12409920.html