LeetCode142. Linked List Cycle II

文章目录

一、题目

Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null.

There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to (0-indexed). It is -1 if there is no cycle. Note that pos is not passed as a parameter.

Do not modify the linked list.

Example 1:

Input: head = 3,2,0,-4, pos = 1

Output: tail connects to node index 1

Explanation: There is a cycle in the linked list, where tail connects to the second node.

Example 2:

Input: head = 1,2, pos = 0

Output: tail connects to node index 0

Explanation: There is a cycle in the linked list, where tail connects to the first node.

Example 3:

Input: head = 1, pos = -1

Output: no cycle

Explanation: There is no cycle in the linked list.

Constraints:

The number of the nodes in the list is in the range 0, 104.

-105 <= Node.val <= 105

pos is -1 or a valid index in the linked-list.

Follow up: Can you solve it using O(1) (i.e. constant) memory?

二、题解

cpp 复制代码
/**
 * 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) {
        ListNode* fast = head;
        ListNode* slow = head;
        while(fast && fast->next){
            fast = fast->next->next;
            slow = slow->next;
            if(fast == slow){
                ListNode* tmp1 = fast;
                ListNode* tmp2 = head;
                while(tmp1 != tmp2){
                    tmp1 = tmp1->next;
                    tmp2 = tmp2->next;
                }
                return tmp1;
            }
        }
        return NULL;
    }
};
相关推荐
小白羊丨36 分钟前
如何诊断 Prompt 模板导致的效果下降?
人工智能·算法·prompt
一木 之林1 小时前
五、C++ 新特性、关键字与编译原理(进阶)(二)
java·开发语言·c++
OPEN-F2 小时前
C++11/14新特性精讲:移动语义与智能指针实战
开发语言·c++·算法
闭月之泪舞2 小时前
C++编程学习
c++·学习
lisin-lee-cooper2 小时前
【leetcode658】有序数组找出k个最接近x的数
java·数据结构·算法
sunburn-2 小时前
Java堆(Heap)详解与实战教学
java·开发语言·数据结构·ide·算法
智碳能碳管理平台3 小时前
工业能耗台账标准化:能碳管理系统的数据口径怎么设计
算法·能碳管理系统·智碳能碳管理平台·企业能碳管理系统·碳排放核算软件·绿色工厂申报saas·能碳管理平台
带多刺的玫瑰3 小时前
Leecode#15刷题之三数之和
算法·leetcode·职场和发展
圣保罗的大教堂3 小时前
leetcode 877. 石子游戏 中等
leetcode
哭泣方源炼蛊4 小时前
并查集进阶 P1(带权并查集,并查集分类)
数据结构·c++·算法·二进制·带权并查集