力扣打卡——环形链表 两题快速理解

发布时间:2026/5/27 8:58:03

力扣打卡——环形链表 两题快速理解 目录141. 环形链表 - 力扣LeetCode142. 环形链表 II - 力扣LeetCode141. 环形链表 - 力扣LeetCode思考设置两个指针一个每次走一步的慢指针和一个每次走两步的快指针。如果不含有环跑得快的那个指针最终会遇到 null说明链表不含环。如果含有环快指针会超慢指针一圈和慢指针相遇说明链表含有环。/** * 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) { //快慢指针进行比对 if(head null) return false; ListNode slowhead; ListNode fasthead; while(fast.next!null fast.next.next!null){ slowslow.next; fastfast.next.next; if(fastslow) return true; } return false; } }142. 环形链表 II - 力扣LeetCode思路快慢指针前进slow走 1 步fast走 2 步第一次相遇 链表一定有环一个指针回到头部一个在相遇点两个指针都走 1 步再次相遇的位置就是环的入口无环直接 returnnull/** * 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 fasthead; ListNode slowhead; while(fast!null fast.next!null){ slowslow.next; fastfast.next.next; //第一次相遇 if(slowfast){ ListNode node1slow; ListNode node2head; //找到入口 while(node1!node2){ node1node1.next; node2node2.next; } return node1; } } return null; } }

相关新闻