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

    /**
     * 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) return false;
            ListNode* fast = head;
            ListNode* slow = head;
            while (step(fast, 2) && step(slow, 1)) {
                if (fast == slow) break;
            }
            return fast != NULL;
        }
        
        bool step(ListNode* &node, int n) {
            while (node != NULL && n > 0) {
                node = node->next;
                n--;
            }
            return n == 0;
        }
    };

    水一发

    第二轮:

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

    Follow up:
    Can you solve it without using extra space?

    必做题

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     bool hasCycle(ListNode *head) {
    12         if (head == NULL) {
    13             return false;
    14         }
    15         ListNode* fast = head->next;
    16         ListNode* slow = head;
    17         while (fast != NULL && fast->next != NULL) {
    18             if (fast == slow) {
    19                 break;
    20             }
    21             slow = slow->next;
    22             fast = fast->next->next;
    23         }
    24         return fast == slow;
    25     }
    26 };
  • 相关阅读:
    【mybatis】02-spring集成
    【Spring】xxAware
    【性能调优】Arthas
    【算法】其他算法(字典树Trie等)
    【多线程】JDK源码类图
    POJ-1251-Jungle Roads
    Prim算法模板
    敌兵布阵-线段树(1)
    hdu-1541-Stars (树状数组)
    母牛生小牛
  • 原文地址:https://www.cnblogs.com/lailailai/p/3805549.html
Copyright © 2011-2022 走看看