Linked List Cycle II
2016-03-14 21:41
531 查看
问题描述:
Given a linked list, return the node where the cycle begins. If there is no cycle, return
Note: Do not modify the linked list.
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) return null;
ListNode fast=head;
ListNode slow=head;
do{
if(fast!=null) fast=fast.next;
if(fast!=null){
fast=fast.next;
}else{
return null;
}
slow=slow.next;
}while(fast != slow);
slow=head;
while(fast!=slow){
fast=fast.next;
slow=slow.next;
}
return slow;
}
}
Given a linked list, return the node where the cycle begins. If there is no cycle, return
null.
Note: Do not modify the linked list.
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) return null;
ListNode fast=head;
ListNode slow=head;
do{
if(fast!=null) fast=fast.next;
if(fast!=null){
fast=fast.next;
}else{
return null;
}
slow=slow.next;
}while(fast != slow);
slow=head;
while(fast!=slow){
fast=fast.next;
slow=slow.next;
}
return slow;
}
}
相关文章推荐
- 只有程序员看的懂的面试圣经|如何拿下编程面试
- 下一次技术面试时要问的 3 个重要问题
- PHP程序员面试 切忌急功近利(更需要注重以后的发展)
- C#常见算法面试题小结
- php 面试碰到过的问题 在此做下记录
- asp.net 面试+笔试题目第1/2页
- asp.net 面试 笔试题目[附答案]第1/3页
- Python爬虫工程师面试问题总结
- 谈谈最近深圳找工作经历
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- 面试:(设计,架构)
- PHP中级面试经历
- 戴维营教育2015年iOS暑期班笔试面试基础考核题
- 一次有意思的面试
- 程序员编程面试取胜的8个技巧
- PHP相关面试中最经常涉及的12个问题