【leetcode82】Linked List Cycle
来源:互联网 发布:分光计实验的数据记录 编辑:程序博客网 时间:2024/05/17 06:32
题目描述:
判断有序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; }}
更多leetcode题目,请看我的leetcode专栏。链接如下:
leetcode专栏
我的微信二维码如下,欢迎交流讨论
欢迎关注《IT面试题汇总》微信订阅号。每天推送经典面试题和面试心得技巧,都是干货!
微信订阅号二维码如下:
2 1
- 【leetcode82】Linked List Cycle
- leetcode Linked List Cycle & Linked List Cycle ||
- Linked List Cycle II Linked List Cycle
- 【LeetCode】Linked List Cycle
- Leetcode: Linked List Cycle
- Leetcode Linked List Cycle
- Linked List Cycle
- Linked List Cycle II
- Linked List Cycle
- Linked List Cycle
- Linked List Cycle II
- Leetcode: Linked List Cycle
- LeetCode:Linked List Cycle
- Linked List Cycle II
- Linked List Cycle
- Linked List Cycle II
- [LeetCode]Linked List Cycle
- Linked List Cycle
- Swift基础语法-类,类的恒等运算
- Mysql book notes
- ARM寄存器
- 定时器初始化源代码
- [Anaconda] command not found: conda
- 【leetcode82】Linked List Cycle
- Matlab Tricks(十四)—— 某一行/列是否在一个矩阵中(ismember)
- HDU 5776 sum ( BC #85 1001)
- 工作两年小结----勿忘初心不负梦想
- hdu4876 暴搜剪枝
- HashMap源码解析
- Android N(SDK7.0)新特性
- Mui前端常用标签
- POJ3261之后缀数组