leetcode141 Linked List Cycle
来源:互联网 发布:锥螺纹怎么编程 编辑:程序博客网 时间:2024/06/06 03:44
Given a linked list, determine if it has a cycle in it.
题目要求是给定一个链表,判断链表里是否有循环。有循环的链表如下图所示:
判断是否有循环,可以用到双指针思想--快慢指针。设置两个指针P_fast和P_slow,快指针的步长是2,慢指针的步长是1,如果有循环的话最终快指针和慢指针会相遇,即:P_fast==P_slow,这里在循环里,快指针不可能跳过慢指针,只要有循环,肯定会相遇,因为每次两指针的距离缩短一个单位。详细Java代码如下所示:
/** * 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) { /***two pointers***/ ListNode p_fast=head; ListNode p_slow=head; while(p_fast!=null&&p_fast.next!=null)//这里的判断条件很重要 { p_fast=p_fast.next.next; p_slow=p_slow.next; if(p_fast==p_slow) return true; } return false; }}这里说一下while循环的判断条件,因为fast指针比slow指针快,所以只需要判断fast和fast.next不为空即可。
0 0
- LeetCode141:Linked List Cycle
- leetcode141. Linked List Cycle
- leetcode141: Linked List Cycle
- leetcode141 Linked List Cycle
- LeetCode141. Linked List Cycle
- leetcode141. Linked List Cycle
- leetcode141~Linked List Cycle
- LeetCode141. Linked List Cycle
- leetcode141. Linked List Cycle
- Leetcode141. Linked List Cycle
- Leetcode141. Linked List Cycle
- leetcode141. Linked List Cycle
- LeetCode141. Linked List Cycle
- Leetcode141. Linked List Cycle
- Leetcode141. Linked List Cycle
- LeetCode141—Linked List Cycle
- LeetCode141之Linked List Cycle java题解
- Leetcode141 - Linked List Cycle(链表)
- 决策树分类ID3算法的Python实现
- geoserver样式浅析2
- 2016/10/20
- 【Java并发】JAVA并发编程实战-读书笔记6
- 主席树解析
- leetcode141 Linked List Cycle
- 皇后问题!
- 数据结构--统计叶子树
- 双线程检测绿色和红色物体(opencv)
- hibernate异常分析:org.hibernate.ObjectNotFoundException
- 编程书籍
- Xcode 的基本操作
- 半数集问题
- POj1862 求一组数据中经过某个运算后的最小值