leetcode【链表】-----141. Linked List Cycle(环形链表)

1、题目描述

2、分析

        这道题一开始想到的方法是哈希表,将每一个指针指向的地址和出现次数存入一个哈希表,这样可以在遍历一次链表的情况下得到结果,只要有一个指针的指向的地址出现两次就可以证明链表里有环。相反如果说明链表没有环。

        还有一种更简单的方法是,使用快慢指针,如果链表有环,那么两个指针肯定会有一个时刻是相等的,具体证明可以参考leetcode官方解释。

3、代码

/**
 * 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&&fast->next){
            fast=fast->next->next;
            slow=slow->next;
            if(slow==fast) return true;
        }
        return false;
        
    }
};
//哈希表
class Solution {
public:
    bool hasCycle(ListNode *head) {
        unordered_map<ListNode*,int> m;
        ListNode *temp=head;
        while(temp!=NULL){
            if(++m[temp]>1) return true;
            temp=temp->next;
        }
        return false;
        
    }
};

4、相关知识点

        常规的哈希方法应该记住。快慢指针的方法了解。

posted @ 2019-04-12 19:01  吾之求索  阅读(82)  评论(0)    收藏  举报