zoukankan      html  css  js  c++  java
  • Linked List Cycle

    /*
        开始用hash做的,但这明显不是最优的
    */
    /**
     * 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) {
            map<ListNode *,int>m;
            while(head){
                if(m[head]) return true;
                m[head] = 1;
                head = head->next;
            }
            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) {
            if(!head) return false;
            ListNode *p1 = head,*p2 = head->next;
            while(p1&&p2&&p2->next){//{},{1}这种都没有圈
                p1 = p1->next;
                p2 = p2->next->next;
                if(p1 == p2) return true;
            }
            return false;
        }
    };
  • 相关阅读:
    OI 知识总览 算法篇 之 动态规划
    LeetCode 16.3Sum Closest
    LeetCode 1.Two sum
    leetCode 15. 3Sum
    leetCode 54. Spiral Matrix
    mybatis(视频)
    mybatis
    spring笔记
    Spring(一)
    Spring(二)
  • 原文地址:https://www.cnblogs.com/llei1573/p/4339686.html
Copyright © 2011-2022 走看看