leetcode:142. Linked List Cycle II(Java)解答
2015-12-27 16:36
471 查看
转载请注明出处:z_zhaojun的博客
原文地址:/article/3591780.html
题目地址:https://leetcode.com/problems/linked-list-cycle-ii/
解法(Java):
原文地址:/article/3591780.html
题目地址:https://leetcode.com/problems/linked-list-cycle-ii/
Linked List Cycle II
[code]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?
解法(Java):
[code]/** * 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.next; while (slow != null && fast != null && slow != fast) { // if (slow == fast) { // temp = slow; // break; // } slow = slow.next; fast = fast.next == null ? fast.next : fast.next.next; } if (slow == fast) { slow = head; fast = fast.next; while (slow != fast) { slow = slow.next; fast = fast.next; } return slow; } return null; } }
相关文章推荐
- ThreadPoolTaskExecutor提高服务器响应速度
- java中的控制执行流程
- 使用Eclipse导出java.doc中文乱码问题
- 从头认识java-15.1 填充容器(3)-填充Map
- spring-context-4.0内的配置
- [JavaWeb基础] 030.dom4j读取xml的4种方法
- Spring之访问(消费)WebService
- Java突击学习 Day2 Part2
- struts2对action中的方法进行输入校验---xml配置方式(3)
- 【Java EE 学习 79 下】【动态SQL】【mybatis和spring的整合】
- MyEclipse下安装本地的安卓插件
- [JavaWeb基础] 029.OGNL表达式介绍
- Java访问修饰符
- Java进阶(五十三)屡试不爽之正则表达式
- Java进阶(五十三)屡试不爽之正则表达式
- 关于java中的操作符
- Struts2之文件下载
- JAVA基础之原始类型变量
- Struts2之文件上传(单文件/多文件)
- Echache整合Spring缓存实例讲解