Linked List Cycle II
来源:互联网 发布:红旗linux官网 编辑:程序博客网 时间:2024/06/06 14:08
Q:
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?
Solution:
/** * 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) { if (head == null || head.next == null) return null; ListNode slow = head; ListNode fast = head; while (fast.next != null) { slow = slow.next; fast = fast.next.next; if (fast == null) return null; if (fast == slow) { slow = head; while (slow != fast) { slow = slow.next; fast = fast.next; } return slow; } } return null; }}
0 0
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- 为什么要写博客
- 【ThinkingInC++】67、多态性和虚函数
- QT中的buttonbox、QMessageBox等默认控件如何显示中文
- HTML5页跳转到Native页面-监听机制
- Android 高仿微信实时聊天 基于百度云推送
- Linked List Cycle II
- C++中#if #ifdef 的作用
- 黑马程序员-关于C语言多文件联合输出
- cocoaPods的安装和使用
- 反射
- 百度Push(云推送)使用基础篇
- centOS7.0设置默认进入字符界面
- Why Singletons are Evil
- 【Linux入门学习之】vi/vim编辑器必知必会