leetcode 141 环形链表

简介: leetcode 141 环形链表

环形链表

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(head==nullptr || head->next==nullptr) return false;
        ListNode *left = head;
        ListNode *right = head;
        while(left!=nullptr && right !=nullptr && right->next!= nullptr)
        {
            left = left->next;
            right = right->next->next;
            if(left == right) return true;
        }
        return false;
    }
};

高频题

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool hasCycle(ListNode *head) {
        ListNode* left = head;
        ListNode* right = head;
        while(right != NULL && right->next != NULL)
        {
            left = left->next;
            right = right->next->next;
            if(left == right) return true;
        }
        return false;
    }
};
相关文章
|
6天前
LeetCode链表hard 有思路?但写不出来?
LeetCode链表hard 有思路?但写不出来?
|
6天前
|
索引
每日一题:力扣328. 奇偶链表
每日一题:力扣328. 奇偶链表
14 4
|
7天前
leetcode代码记录(移除链表元素
leetcode代码记录(移除链表元素
11 0
【每日一题】LeetCode——反转链表
【每日一题】LeetCode——反转链表
【每日一题】LeetCode——链表的中间结点
【每日一题】LeetCode——链表的中间结点
|
6天前
|
C++
[leetcode 链表] 反转链表 vs 链表相交
[leetcode 链表] 反转链表 vs 链表相交
|
6天前
【力扣】148. 排序链表
【力扣】148. 排序链表
|
6天前
|
索引
【力扣】142. 环形链表 II
【力扣】142. 环形链表 II
|
7天前
|
算法
LeetCode刷题---19. 删除链表的倒数第 N 个结点(双指针-快慢指针)
LeetCode刷题---19. 删除链表的倒数第 N 个结点(双指针-快慢指针)
|
7天前
|
存储
LeetCode刷题---817. 链表组件(哈希表)
LeetCode刷题---817. 链表组件(哈希表)

热门文章

最新文章