环形链表 LC141&142

2020-01-17  本文已影响0人  锦绣拾年

lc141

给定一个链表,判断链表中是否有环。

为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。


示例 1:

输入:head = [3,2,0,-4], pos = 1
输出:true
解释:链表中有一个环,其尾部连接到第二个节点。


示例 2:

输入:head = [1,2], pos = 0
输出:true
解释:链表中有一个环,其尾部连接到第一个节点。


示例 3:

输入:head = [1], pos = -1
输出:false
解释:链表中没有环。


来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/linked-list-cycle
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

1、哈希表
注意点:
如何存指针 判断是否已存在:set数据结构的使用
set insert 方法 count方法(值为0或者1)

/**
 * 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) {
        set<ListNode*> tmp;
        if(head)
            tmp.insert(head);
        else
            return false;
            
        while(head->next){
            if(tmp.count(head->next)==1)
                return true;
            else
                tmp.insert(head->next);
            head=head->next;
        }
        return false;
        
    }
};

2、双指针法
快慢指针

/**
 * 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||!head->next)
            return false;
        ListNode *fast=head->next->next;
        ListNode *slow=head->next;
        while(fast!=slow){
            slow=slow->next;
            if(fast&&fast->next)
                fast=fast->next->next;
            else
                return false;
        }
        if(fast)
            return true;
        else
            return false;
        
    }
};

LC142

难点:如何清楚地解释寻找环入口的过程

/**
 * 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 * tmp;
       if(!head||!head->next)
            return NULL;
        ListNode *fast=head->next->next;
        ListNode *slow=head->next;
        while(fast!=slow){
            slow=slow->next;
            if(fast&&fast->next)
                fast=fast->next->next;
            else
                return NULL;
        }
        if(!fast)
            return NULL;
        
        ListNode *pre=fast;
        ListNode *now=head;
        while(now!=pre){
            now=now->next;
            pre=pre->next;
        }
        return now;
            
        
    }
};
上一篇 下一篇

猜你喜欢

热点阅读