LeetCode 142. Linked List Cycle II
来源:互联网 发布:sql优化书籍推荐 编辑:程序博客网 时间:2024/06/08 15:58
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?
对于寻找重合点来说,必须要是用快慢指针,因此slow = head
fast = head.next
java
# Definition for singly-linked list.# class ListNode(object):# def __init__(self, x):# self.val = x# self.next = Noneclass Solution(object): def detectCycle(self, head): """ :type head: ListNode :rtype: ListNode """ if head is None or head.next is None: return None node = self.getCycle(head) if node is None: return None while head is not node.next: node = node.next head = head.next return head def getCycle(self, head): if head is None or head.next is None: return None slow, fast = head, head.next while fast.next is not None and fast.next.next is not None: if fast == slow: return slow else: fast = fast.next.next slow = slow.next return None
python
/** * 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 node = getCycle(head); if (node == null) { return null; } while (head != node.next) { head = head.next; node = node.next; } return head; } private ListNode getCycle(ListNode head) { if (head == null || head.next == null) { return null; } ListNode slow = head; ListNode fast = head.next; while (fast.next != null && fast.next.next != null) { if (fast == slow) { return slow; } fast = fast.next.next; slow = slow.next; } return null; }}
阅读全文
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
- 马尔科夫随机场(MRF)与吉布斯分布(Gibbs)
- spacy库安装
- Dynpro程序抬头信息要求多值输入的解决方法
- leetcode 3. Longest Substring Without Repeating Characters
- centos 下安装gcc vim gdb
- LeetCode 142. Linked List Cycle II
- PLSQL Developer连接Oracle11g 64位数据库配置详解
- Android多语言切换,字体风格,简体转繁体
- android studio导入项目出错:Error:Execution failed for task ':app:processDebugManifest'. > Manifest merger
- Java实现哈夫曼树(HuffmanTree)
- github上最全的资源教程-前端涉及的所有知识体系
- Android中<meta-data>的使用
- 计算并分析k和n的值。
- Spring注解原理的详细剖析与实现