141. 环形链表

141. 环形链表

解法一:所到之处,寸草不生

第一种解法自己写的,巧妙运用了链表的val,只要遍历过,就将节点的值设置为1e9,时间空间复杂度都达到了完美的统一(doge)

/**
 * 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 == NULL) return false;
        ListNode* cur = head;

        while(cur->next){
            cur->val = 1e9;
            if(cur->next->val == 1e9) return true;
            cur = cur->next;
            // if(cur->next == head) return true;
            // else{cur = cur->next;}    
        }
        return false;
    }
};

看评论区还有将链表指向直接给改了的,只能说为了解题老本都豁出去了,hhh

还是用官方经典的做法吧

双指针

/**
 * 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* fast = head;
        ListNode* slow = head;

        while(fast != nullptr && fast->next != nullptr) {
            fast = fast ->next->next;
            slow = slow->next;
            if(fast == slow)return true;
        }
        return false;
    }
};

这里开辟的空间只有两个指针,空间复杂度为O(1).

posted @ 2023-04-06 10:37  luxiayuai  阅读(24)  评论(0)    收藏  举报