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
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode:
- leetcode
- 170221
- 数据库设计的重要性和设计原则
- Google C++测试单元工具 gtest(二)
- 《数据库系统概论》课程指南
- RxJava 之二—— Lift()详解
- LeetCode
- 顺序表的动态申请空间版本
- swift学习笔记(12)- 继承
- iOS计算时间差-倒计时时间
- MongoDB
- 解决图片上下居中问题
- Material Design
- HTML表单
- canvas.save和canvas.restore的作用