[LeetCode] Linked List Cycle II

简介: Again, a classic interview question of linked list. Similar to Linked List Cycle, we maintain two pointers fast and slow: fast move two steps at one time while slow moves one step at a time.

Again, a classic interview question of linked list. Similar to Linked List Cycle, we maintain two pointers fast and slow: fast move two steps at one time while slow moves one step at a time. Once they become NULL, return NULL (no cycle). Otherwise, they will equal at some time. At this time, move any one of them back to head and then move both of them one step at a time. Then they will meet at the same node again. At this time, that node is where the cycle begins. Return it and we are done.

The code is as follows.

 1     ListNode* detectCycle(ListNode* head) {
 2         ListNode* slow = head;
 3         ListNode* fast = head;
 4         while (fast && fast -> next) {
 5             slow = slow -> next;
 6             fast = fast -> next -> next;
 7             if (slow == fast) {
 8                 slow = head;
 9                 while (slow != fast) {
10                     slow = slow -> next;
11                     fast = fast -> next;
12                 }
13                 return slow;
14             }
15         }
16         return NULL;
17     }
目录
相关文章
|
6月前
|
Java
Leetcode 114. Flatten Binary Tree to Linked List
思路也很简单,先把root的左子树(如有)变成单链表 leftlinkedlist,把root的右子树(如有)变成单链表 rightlinkedlist,再把root的右节点变成leftlikedlist,再把rightlinkedlist接到leftlinkedlist后面,代码如下。
21 1
|
6月前
|
C++
Leetcode Copy List with Random Pointer(面试题推荐)
给大家推荐一道leetcode上的面试题,这道题的具体讲解在《剑指offer》的P149页有思路讲解,如果你手头有这本书,建议翻阅。
28 0
|
6月前
Leetcode 19.Remove Nth Node From End of List
删除单链表中的倒数第n个节点,链表中删除节点很简单,但这道题你得先知道要删除哪个节点。在我的解法中,我先采用计数的方式来确定删除第几个节点。另外我在头节点之前额外加了一个节点,这样是为了把删除头节点的特殊情况转换为一般情况,代码如下。
21 0
|
1天前
|
大数据 Java 程序员
「LeetCode合集」链表(List)及经典问题
「LeetCode合集」链表(List)及经典问题
28 0
|
11月前
|
C++
【PAT甲级 - C++题解】1133 Splitting A Linked List
【PAT甲级 - C++题解】1133 Splitting A Linked List
54 0
|
11月前
|
C++
【PAT甲级 - C++题解】1074 Reversing Linked List
【PAT甲级 - C++题解】1074 Reversing Linked List
48 0
|
11月前
|
机器学习/深度学习 存储 C++
【PAT甲级 - C++题解】1052 Linked List Sorting
【PAT甲级 - C++题解】1052 Linked List Sorting
60 0
二叉树(Binary Tree)的二叉链表(Binary Linked List)实现
二叉树(Binary Tree)的二叉链表(Binary Linked List)实现
|
存储 C++
线性表的链式存储结构 单链表(Singly Linked List) C++
线性表的链式存储结构 单链表(Singly Linked List) C++
LeetCode 141. 环形链表 Linked List Cycle
LeetCode 141. 环形链表 Linked List Cycle