LeetCode141. Linked List Cycle

来源:互联网 发布:5s是否支持4g网络 编辑:程序博客网 时间:2024/09/21 08:57

description:
Given a linked list, determine if it has a cycle in it.

解题思路:
这一道题目主要是使用快慢指针的方式进行处理。
其中要判断快指针的point 和 next是否为null,是为了避免空指针异常。
这一题目没有bugfree,就是因为空指针异常。

/** * 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 slow = head;        ListNode fast = head.next;        while (fast != slow) {            if (fast == null || fast.next == null) {                return false;            }            fast = fast.next.next;            slow = slow.next;        }        return true;    }}
0 0
原创粉丝点击