leetcode(38).141. Linked List Cycle

来源:互联网 发布:测试交换机端口带宽 编辑:程序博客网 时间:2024/06/03 13:22

题意:给定一个链表,判断其中是否有循环存在。

初步分析:看到这个题,第一反应就是用两个指针来玩它,第二反应就是快慢指针跟着绕。

如果有循环!那么,快慢指针一定会相遇

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


0 0