LeetCode 142: Linked List Cycle II
来源:互联网 发布:windows 损坏的图像 编辑:程序博客网 时间:2024/05/16 19:14
一 题目
Given a linked list, return the node where the cycle begins. If there is no cycle, return
Can you solve it without using extra space?
null
.Note: Do not modify the linked list.
Follow up:Can you solve it without using extra space?
题意:判断一个链表中是否存在环,返回这个环的起点,如果不存在,请返回null。
问题分析:
1.首先如何判断一个链表中存在环呢?
定义两个指针,一个快指针fast,一个慢指针slow,快指针每次走两个节点,慢指针每次走一个节点。如果fast碰到null,说明此链表无环,如果slow == fast ,说明链表中存在环。因为在环形结构中,fast指针移动超越了slow指针一段距离,而这种情况,在无环的情况下是不存在的,就好比一条笔直的马路,跑的快的,永远在跑的慢的前面,如果是一个圈,那跑的快的一定会超越跑的慢的一圈,两圈,……,肯定会相遇。
2.如何找到环的起点
如图,X为链表的起点,Y为环的起点,而Z为fast和slow相遇的地方。
当slow走到Z时,他所走过的落成为a+b,而当fast走到Z时,他所走的距离为a+b+c+b,因为fast的速度是slow的两倍,所以有
2*(a+b) = a +b+ c + b,因此可以瑞出 a = c。
这个题的解题思路:
当fast和slow相遇时,此时重新定义一个指针从X位置开始移动,slow从Z开始移动,直到两个指针相遇,因为a = c,所以两个指针相遇的地方就是环开始的地方。
代码如下:
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public ListNode detectCycle(ListNode head) { ListNode slow = head; ListNode fast = head; while(fast!=null && fast.next!=null){ slow = slow.next; fast = fast.next.next; if(slow == fast){ ListNode slow2 = head; while(slow !=slow2){ slow2 = slow2.next; slow = slow.next; } return slow; } } return null; }}
阅读全文
0 0
- LeetCode.142(141) Linked List Cycle && Linked List Cycle (II)
- LeetCode 142 Linked List Cycle II
- LeetCode 142 Linked List Cycle II
- LeetCode: Linked List Cycle II [142]
- [leetcode 142]Linked List Cycle II
- Leetcode NO.142 Linked List Cycle II
- [leetcode]142 Linked List Cycle II
- [LeetCode 142]Linked List Cycle II
- leetcode || 142、Linked List Cycle II
- 【leetcode】【单链表】【142】Linked List Cycle II
- [Leetcode 142] Linked List Cycle II
- [leetcode-142]Linked List Cycle II(c)
- leetcode 142: Linked List Cycle II
- leetCode #142 Linked List Cycle II
- Leetcode #142 Linked List Cycle II
- 142 Linked List Cycle II [Leetcode]
- 【LEETCODE】142-Linked List Cycle II
- LeetCode 142 Linked List Cycle II
- Retrofit2.0的基本使用
- jsp 页面添加取消滚动条
- 我的第一篇博客
- 自己实现HTTP服务器
- Tomcat Context.xml添加<Loader delegate="true"/>
- LeetCode 142: Linked List Cycle II
- 微信小程序支付
- title内容换行(VUE)
- 347. Top K Frequent Elements
- sql server数据库备份还原
- spring 自定参数解析器(HandlerMethodArgumentResolver)
- 上传本地代码到github上面,怎么忽略node_modules文件夹
- Codeforces Vanya and Lanterns
- 欢迎使用CSDN-markdown编辑器