Linked List Cycle II
来源:互联网 发布:双十一淘宝大数据 编辑:程序博客网 时间:2024/06/05 19:46
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?
/** * 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 || head.next.next == null){ return null; } ListNode p1 = head; ListNode p2 = head.next.next; while(p2 != null){ if(p1 == p2){ break; } p1 = p1.next; if(p2.next == null || p2.next.next == null){ return null; } p2 = p2.next.next; } int circleLen = 0;//链长 do{ circleLen++; p2 = p2.next; }while(p1 != p2); int c = 0; p1 = head; p2 = head; while(c < circleLen){ c++; p2 = p2.next; } while(p1 != p2){ p1 = p1.next; p2 = p2.next; } return p1; }}
Runtime: 396 ms
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
- 让spring mvc支持put请求
- 记录一些网摘
- C++ 函数的覆盖
- Go开发笔记
- 解决XCode6.1 iOS8.1使用storyboard屏幕适配问题
- Linked List Cycle II
- 走向面试之数据库基础:一、你必知必会的SQL语句练习-Part 1
- Linux的标准输入、输出,错误
- study matlab(4)
- java中的X509EncodedKeySpec类
- 走向面试之数据库基础:一、你必知必会的SQL语句练习-Part 2
- OPENERP创建用户(权限设置、密码修改)
- log4net 配置备忘
- MongoDB 新建数据库用户例子