141. Linked List Cycle

题目

原始地址:https://leetcode.com/problems/linked-list-cycle/#/description

/**
 * 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) {
        
    }
}

描述

给定一个单链表,判断它是否有环。

分析

经典链表题目,难点在于如果链表有环,那么使用循环时很容易出现死循环的情况。
如果允许分配空间,很容易想到使用一个容器把遍历过的节点保存起来,每次读取下个节点时判断一下是否已经遍历过即可。
题目要求不使用额外空间,所以使用快慢指针的算法。分配两个指针walker和runner,walker每次前进一步,runner每次前进两步,如果链表中有环,那么它们最终肯定会到环中相遇,否则会走到链表尾端。

解法

/**
 * 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 (head == null || head.next == null) {
            return false;
        }
        ListNode walker = head, runner = head.next;
        while (runner != null && runner.next != null && runner != walker) {
            runner = runner.next.next;
            walker = walker.next;
        }
        return runner == walker;
    }
}
posted @ 2017-04-30 22:08  北冥尝有鱼  阅读(102)  评论(0编辑  收藏  举报