LeetCode

来源:互联网 发布:管家的面 淘宝 编辑:程序博客网 时间:2024/06/06 16:00

题目:

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


思路与步骤:

采用“快慢指针”查检查链表是否含有环。让一个指针一次走一步,另一个一次走两步,如果链表中含有环,快指针会再次和慢指针相遇。


编程实现:

/** * 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;        ListNode slow = head;        while(fast.next!=null && fast.next.next!=null){            fast = fast.next.next;            slow = slow.next;            if(fast==slow)  return true;        }        return false;    }}
注意循环条件!否则会有异常

while(fast.next!=null && fast.next.next!=null)

0 0
原创粉丝点击