Leetcode: Linked List Cycle II
来源:互联网 发布:淘宝店保健品不让上架 编辑:程序博客网 时间:2024/06/03 20:01
题目:
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
思路分析:
和《Leetcode: Linked List Cycle 》一样还是双指针的方法。
一个循环链表如图
slow指针走了S=X+Y
fast指针走了F=X+Y+Z+Y
两个指针相遇。
且有:2S=F,则有X=Z。
所以,从head到环开始的路程 = 从相遇到环开始的路程。
所以,当slow和fast相遇了,我们拿slow从头开始走,fast从相遇的地方开始走,两个都走一步,那么再次相遇必定是环的开始节点。
C++参考代码:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution{public: ListNode *detectCycle(ListNode *head) { if (!head) return nullptr; ListNode *slow = head; ListNode *fast = head; bool hasCycle = false; while (fast && fast->next) { slow = slow->next; fast = fast->next->next; if (slow == fast) { hasCycle = true; break; } } if (hasCycle) { slow = head; while (slow != fast) { slow = slow->next; fast = fast->next; } return slow; } else return nullptr; }};
C#参考代码:
/** * Definition for singly-linked list. * public class ListNode { * public int val; * public ListNode next; * public ListNode(int x) { * val = x; * next = null; * } * } */public class Solution{ public ListNode DetectCycle(ListNode head) { if (head == null) return null; ListNode slow = head; ListNode fast = head; bool hasCycle = false; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; if (slow == fast) { hasCycle = true; break; } } if (hasCycle) { slow = head; while (slow != fast) { slow = slow.next; fast = fast.next; } return slow; } else return null; }}
0 0
- 【LeetCode】 Linked List Cycle II
- Leetcode: Linked List Cycle II
- <Leetcode>Linked List Cycle II
- [LeetCode] Linked List Cycle II
- Leetcode: Linked List Cycle II
- LeetCode:Linked List Cycle II
- Leetcode Linked List Cycle II
- [LeetCode]Linked List Cycle II
- leetcode Linked List Cycle II
- LeetCode | Linked List Cycle II
- Leetcode: Linked List Cycle II
- [LeetCode] - Linked List Cycle II
- Leetcode: Linked List Cycle II
- LeetCode - Linked List Cycle II
- leetcode Linked List Cycle II
- Linked List Cycle II -- LeetCode
- LeetCode Linked List Cycle II
- [LeetCode] Linked List Cycle II
- Android HOOK工具Cydia Substrate使用详解
- Python基础教程中的函数
- Java_socket程序学习0501-彩票销售-第一阶段server端整理-失败
- uedit使用技巧2
- 喜羊羊系列之linux网络服务设置(nfs,tftp,samba)
- Leetcode: Linked List Cycle II
- 回调方法2
- Ubuntu 14.04安装Linux源码
- Java基础--简述JRE、JVM、JDK之间的关系与Java基础知识点
- Java设计模式--单例模式
- 【Objective-C学习笔记】核心语法——类的本质、description方法
- 安卓学习笔记01
- 两种方式求1--100以内所有相邻奇偶数之积的和
- Java基础--多线程