题目描述:
判断有序list是不是环
要求:
时间复杂度o(n)
原文描述:Given a linked list, determine if it has a cycle in it.
Follow up:Can you solve it without using extra space?
思路:- 设置两个指针,一个快指针,每次走两步,一个慢指针,每次走一步
- 如果块指针==慢指针,那么包含环
- 注意判断空值和长度为一的情况
/**
* 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(slow == fast) {
return true;
}
}
return false;
}
}
點擊查看更多內容
4人點贊
評論
評論
共同學習,寫下你的評論
評論加載中...
作者其他優質文章
正在加載中
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦