[LeetCode] 142. Linked List Cycle II
Given a linked list, return the node where the cycle begins. If there is no cycle, return?null.
題意:找一個(gè)鏈表中是否含有環(huán),如果沒有則返回null,如果有則返回環(huán)的起點(diǎn)
我的解法,投機(jī)取巧了,我改了val的值,再次掃到我改的那個(gè)值就是要的節(jié)點(diǎn)
public class Solution {public ListNode detectCycle(ListNode head) {ListNode n = head;if(n == null || n.next == null)return null;while(n.next != null) {if(n.val == -3276800)return n;n.val = -3276800;n = n.next;}return null;} }二次做這個(gè)題,其實(shí)是做287的時(shí)候,發(fā)現(xiàn)他們說(shuō)是這個(gè)題的變種,我特意回來(lái)重做了一遍
就是用一個(gè)慢指針和一個(gè)快指針,快指針是慢指針的兩倍,他們相遇的時(shí)候(因?yàn)橛协h(huán)的話一定會(huì)相遇。沒有相遇證明沒有)
將slow或者fast指針指向頭,然后步速都變?yōu)?;他們?cè)俅蜗嘤龅臅r(shí)候就是環(huán)的入口;
public class Solution {public ListNode detectCycle(ListNode head) {ListNode n = head;if (n == null || n.next == null) return null;ListNode pre = head.next;ListNode nxt = head.next.next;if (pre == null || nxt == null)return null;while (true) {if (pre == nxt) break;if (pre.next == null) return null;pre = pre.next;if (nxt.next == null) return null;nxt = nxt.next;if (nxt.next == null) return null;nxt = nxt.next;}pre = head;while (pre != nxt) {pre = pre.next;nxt = nxt.next;}return pre;} }?
補(bǔ)充:這個(gè)算法可能很難去理解,這么證明我就不寫了(畢竟本人不擅長(zhǎng)畫圖)
有興趣的小伙伴可以去證明一下,或者大家直接將結(jié)論記住吧
轉(zhuǎn)載于:https://www.cnblogs.com/Moriarty-cx/p/9710737.html
總結(jié)
以上是生活随笔為你收集整理的[LeetCode] 142. Linked List Cycle II的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python中字符串的常见操作方法
- 下一篇: 朱 - 刘算法