14、Visio工具的使用 - 專案管理系列文章
阿新 • • 發佈:2021-12-01
給定一個連結串列,返回連結串列開始入環的第一個節點。如果連結串列無環,則返回null。
如果連結串列中有某個節點,可以通過連續跟蹤 next 指標再次到達,則連結串列中存在環。 為了表示給定連結串列中的環,評測系統內部使用整數 pos 來表示連結串列尾連線到連結串列中的位置(索引從 0 開始)。如果 pos 是 -1,則在該連結串列中沒有環。注意:pos 不作為引數進行傳遞,僅僅是為了標識連結串列的實際情況。
不允許修改 連結串列。
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/linked-list-cycle-ii
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。
心之所向,素履以往 生如逆旅,一葦以航public class Solution { public ListNode detectCycle(ListNode head) { if (head == null || head.next == null || head.next.next == null) { return null; } ListNode slow = head.next, fast = head.next.next; while (fast.next != null && fast.next.next != null) { slow = slow.next; fast = fast.next.next; if (slow == fast) { slow = head; while (slow != fast) { slow = slow.next; fast = fast.next; } return slow; } } return null; } } class ListNode { int val; ListNode next; ListNode(int x) { val = x; next = null; } }