zoukankan      html  css  js  c++  java
  • 判断链表是否又环

    /**
     * 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) {
            if(head == NULL ||head->next == NULL)return NULL;
            ListNode* fast = head;
            ListNode* low = head;
            while(fast && fast->next){
                fast = fast->next->next;
                low = low->next;
                if(fast == low)break;
            }
            
            if(fast != low)return NULL;
            low = head;
            while(1){
                if(fast == low)break;
                low = low->next;
                fast = fast->next;
                
            }
            return low;
        }
    };
    判断是否有环
    
    /**
     * 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 || head->next == NULL)return false;
            ListNode *fast = head;
            ListNode *slow = head;
            while(fast && fast->next){
                slow = slow->next;
                fast = fast->next->next;
                if(slow == fast)return true;
            }
            return false;
        }
    };
    
    
    
     
  • 相关阅读:
    cs224n word2vec
    背包问题
    动态规划二
    动态规划
    递推求解
    Tmux 使用技巧
    LeetCode 75. Sort Colors
    LeetCode 18. 4Sum new
    LeetCode 148. Sort List
    LeetCode 147. Insertion Sort List
  • 原文地址:https://www.cnblogs.com/lyf-sunicey/p/9547784.html
Copyright © 2011-2022 走看看