• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode: Linked List Cycle II

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Follow up:
Can you solve it without using extra space?

一次过,还是Runner Technique的方法

 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         if (head == null || head.next == null) return null;
15         ListNode runner = head;
16         ListNode walker = head;
17         while (runner != null && runner.next != null) {
18             runner = runner.next.next;
19             walker = walker.next;
20             if (runner == walker) break;
21         }
22         if (runner != walker) return null;
23         runner = head;
24         while (runner != walker) {
25             runner = runner.next;
26             walker = walker.next;
27         }
28         return walker;
29     }
30 }

 

posted @ 2014-06-20 08:04  neverlandly  阅读(240)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3