Leetcode Linked List Cycle 循环链表

来源:互联网 发布:mac geforce now 教程 编辑:程序博客网 时间:2024/04/30 02:46


题目:


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


分析:

1. 使用快慢指针,如果有环,快慢指针会相遇,如果没有环,快指针会首先到达null。

2. fast = fast.next.next语句注意fast.next可能已经是null,这是会出现空指针错误。因此,需要先进行判断。


Java代码实现:


/** * 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 fast = head.next.next;        ListNode slow = head.next;                while(fast!=null )        {            if(fast == slow)                return true;            if(fast.next!=null)                fast = fast.next.next;            else                fast = fast.next;            slow = slow.next;        }                return false;    }}


0 0
原创粉丝点击