鱼C论坛

 找回密码
 立即注册
查看: 2951|回复: 0

[学习笔记] Leetcode 141:环形链表

[复制链接]
发表于 2019-8-5 01:00:45 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
2.jpg

  1. /**
  2. * Definition for singly-linked list.
  3. * class ListNode {
  4. *     int val;
  5. *     ListNode next;
  6. *     ListNode(int x) {
  7. *         val = x;
  8. *         next = null;
  9. *     }
  10. * }
  11. */
  12. public class Solution {
  13.     public ListNode detectCycle(ListNode head) {
  14.    
  15.         ListNode slow = head;
  16.         ListNode fast = head;
  17.         ListNode end = null;
  18.         
  19.         while(slow != null && fast != null){
  20.             
  21.             fast = fast.next;
  22.             
  23.             if(fast == null){
  24.                
  25.                 return null;
  26.             }
  27.             
  28.             slow = slow.next;
  29.             fast = fast.next;
  30.             
  31.             if(slow == fast){
  32.                
  33.                 end = slow;
  34.                
  35.                 break;
  36.             }
  37.             
  38.         }
  39.         
  40.         while(end != null && head != null){
  41.             
  42.             if(end == head){
  43.                
  44.                 return head;
  45.                
  46.             }
  47.             
  48.             end = end.next;
  49.             
  50.             head =head.next;
  51.             
  52.         }
  53.         
  54.         return null;
  55.         
  56.     }
  57. }
复制代码

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-8 15:42

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表