【Leetcode】141. Linked List Cycle(链表判环)

版权声明:本文为博主原创文章,未经博主许可允许转载。 https://blog.csdn.net/qq_29600137/article/details/89761067

Given a linked list, determine if it has a cycle in it.

To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.

Example 1:

Input: head = [3,2,0,-4], pos = 1
Output: true
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: true
Explanation: There is a cycle in the linked list, where tail connects to the first node.

Example 3:

Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.

Follow up:

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

 题目大意:

判断给出的链表是否有环。

解题思路:

map容器暴力可ac,但是分析题目中链表的构建通过数组构建,所以可以通过指针地址来判断是否有小地址在大地纸之后。

class Solution {
private:
    unordered_map<int, vector<ListNode*>> dp;
    bool valid(ListNode *tmp){
        for(int i=0;i<dp[tmp->val].size();i++){
            if(tmp==dp[tmp->val][i])
                return false;
        }
        return true;
    }
public:
    bool hasCycle(ListNode *head) {
        if(head==NULL) return false;
        while(head){
            if(valid(head)){
                dp[head->val].push_back(head);
            }else{
                return true;
            }
            
            head=head->next;
            
        }
        return false;
    }
};
class Solution {

public:
    bool hasCycle(ListNode *head) {
    ListNode* cur = head;
    if(cur==NULL){
        return false;
    }
    while(true){
        if(cur->next == NULL){
            return false;
        }else if(cur->next <= cur){
            return true;
        }
        cur=cur->next;
    }
}   
};

猜你喜欢

转载自blog.csdn.net/qq_29600137/article/details/89761067