• [LeetCode] Linked List Cycle


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

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

    思路:快慢指针的应用。快慢指针指的是移动的步长,即每次向前移动的快慢。例如可以让快指针每次沿链表向前移动2,慢指针每次向前移动1次。

       如果快指针到达NULL,说明链表以NULL为结尾,没有环。如果快指针追上慢指针,则表示有环。

       时间复杂度O(n),空间复杂度O(1)

     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) return head;
    13         
    14         ListNode *slow = head, *fast = head;
    15         while (fast != NULL && fast->next != NULL) {
    16             fast = fast->next->next;
    17             slow = slow->next;
    18             if (fast == slow) return true;
    19         }
    20         
    21         return false;
    22     }
    23 };
  • 相关阅读:
    素材收集
    网站返回503
    uva 1048 最短路的建图 (巧,精品)
    hdu5188 01 背包
    hdu 5187 快速幂 + 快速乘 值得学习
    差分约束
    uva11090 Bellman-Ford 运用
    hdu 5185 动态规划 分析降低复杂度
    hdu5184 数论证明
    HDU5183 hash 表
  • 原文地址:https://www.cnblogs.com/vincently/p/4072091.html
Copyright © 2020-2023  润新知