算法系列——Linked List Cycle II
来源:互联网 发布:怎么找放单的淘宝商家 编辑:程序博客网 时间:2024/05/25 12:21
题目描述
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Note: Do not modify the linked list.
解题思路
找到环的入口结点。这是链表问题中的一个经典问题。
比较简单的方法,是先用快慢双指针找到重合位置。然后慢指针从头开始,和快指针 均采用一步速开始遍历,重合位置为环的入口结点。
具体分析可以看这篇博客。
http://www.cnblogs.com/hiddenfox/p/3408931.html
程序实现
public class Solution { public ListNode detectCycle(ListNode head) { if(head==null||head.next==null) return null; ListNode p1=head; ListNode p2=head; while(p2!=null&&p2.next!=null){ p1=p1.next; p2=p2.next.next; if(p1==p2) break; } //p1 从起始位置开始,和p2 if(p1==p2){ p1=head; while(p1!=p2){ p1=p1.next; p2=p2.next; } return p1; } else return null; }}
阅读全文
0 0
- 算法系列——Linked List Cycle II
- 算法系列——Linked List Cycle
- [算法][LeetCode]Linked List Cycle & Linked List Cycle II——单链表中的环
- [算法][LeetCode]Linked List Cycle & Linked List Cycle II——单链表中的环
- LeetCode——Linked List Cycle II
- LeetCode——Linked List Cycle II
- Algorithms—142.Linked List Cycle II
- LeetCode142—Linked List Cycle II
- 【Leetcode长征系列】Linked List Cycle II
- <leetcode系列> Linked List Cycle II
- [LeetCode]Linked List Cycle & Linked List Cycle II——单链表中的环
- LeetCode——141. Linked List Cycle && 142. Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- LintCode 97 验证二叉查找树
- STL学习笔记-迭代器
- python中 Jupter的使用 notebook
- 各大巨头纷纷出手 数据中心市场硝烟弥漫
- java解析json格式数据
- 算法系列——Linked List Cycle II
- Cookie的路径和域
- SimpleDateFormat非线程安全
- 私有网络(腾讯云)
- 【PAT】【Advanced Level】1022. Digital Library (30)
- 位运算
- 随机森林原理介绍
- mybatis(7)--使用mapper代理开发代替原始的dao开发
- h5页面转盘抽奖