LeetCode 142. Linked List Cycle II
来源:互联网 发布:淘宝天下天下网商区别 编辑:程序博客网 时间:2024/06/08 15:45
题目内容
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
题目分析
在141题的基础上,加入了寻找出了环的起点位置,如果有环找出起点,没有环返回null。
找出环的起点,当找到确定有环以后,讲fast标记回head结点,然后步长调整为1,当再次与slow相遇的时候,就是环的开始结点。,参考
单链表判断环
存在问题 这样写有一个问题,就是无法判断环为1-2-1,起始结点即为环的开始结点,且环的大小为2 的情况,需要单独判断。
这个在代码2中也是要判断的,只是代码2特别精简。可以直接读代码2.
代码如下
/** * 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) { ListNode fast=head; ListNode slow=head; boolean flag=false; while(fast!=null&&fast.next!=null) { fast=fast.next.next; slow=slow.next; if (slow==fast) { flag=true; break; } } if (flag==true) { fast=head; if (slow==fast) { return fast; } while(fast!=null&&fast.next!=null) { fast=fast.next; slow=slow.next; if (slow==fast) { return fast; } } } return null; }}
代码2
public ListNode detectCycle(ListNode head) { if (head == null || head.next == null) { return null; // no circle } ListNode slow = head, fast = head; while (fast != null && fast.next != null) { fast = fast.next.next; slow = slow.next; if (fast == slow) { // circle detected while (head != fast) { fast = fast.next; head = head.next; } return head; } } return null; // no circle}
0 0
- [LeetCode]141. Linked List Cycle【&142. Linked List Cycle II】
- leetcode--141. Linked List Cycle&&142. Linked List Cycle II
- LeetCode 141. Linked List Cycle && 142. Linked List Cycle II
- 142. Linked List Cycle II leetcode list
- LeetCode 142. Linked List Cycle II
- [LeetCode]142.Linked List Cycle II
- [leetcode] 142.Linked List Cycle II
- [leetcode] 142. Linked List Cycle II
- leetcode 142. Linked List Cycle II
- [Leetcode]142. Linked List Cycle II @python
- [LeetCode]142. Linked List Cycle II
- 142. Linked List Cycle II LeetCode
- LeetCode:142. Linked List Cycle II
- LeetCode--142. Linked List Cycle II
- LeetCode 142. Linked List Cycle II
- LeetCode 142. Linked List Cycle II
- LeetCode *** 142. Linked List Cycle II
- LeetCode 142. Linked List Cycle II
- 高德地图 鼠标点击后 地图地图上点标记跟着变化
- 基本类型/引用类型的参数传递
- getopt()函数获取两个以上参数的方法
- Android开发实践(五)App的登陆界面
- 第十周第十一周项目3(2)
- LeetCode 142. Linked List Cycle II
- OpenGL Transform feed back 粒子系统
- Spring与Hibernate混合编程(一)
- mysql 学习笔记4
- iOS9横屏竖屏设置
- 如何用微信支付宽带费用、wifi网费
- caffe基础介绍
- 第十一周时间项目(5)——d
- HQL总结