zoukankan      html  css  js  c++  java
  • LeetCode

    Linked List Cycle

    2014.1.13 21:24

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

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

    Solution:

      The problem indicated that you shouldn't use extra space. And you might be wondering why you should use extra space if you could just use two pointers and let the faster one chase up the slower one.

      If extra space is allowed, you can use a hash-table to record the addresses of the nodes. There will be duplicate address if the list contains a cycle.

      I guess you're more familiar with the chasing method, which uses extra chasing time to avoid the space usage in hashing.

      Time complexity is O(n), space complexity is O(1).

    Accepted code:

     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         // IMPORTANT: Please reset any member data you declared, as
    13         // the same Solution instance will be reused for each test case.
    14         if(head == nullptr){
    15             return false;
    16         }
    17         
    18         ListNode *p1, *p2;
    19         
    20         p1 = p2 = head;
    21         while(true){
    22             if(p1->next == nullptr){
    23                 return false;
    24             }
    25             if(p2->next == nullptr || p2->next->next == nullptr){
    26                 return false;
    27             }
    28             
    29             p1 = p1->next;
    30             p2 = p2->next->next;
    31             if(p1 == p2){
    32                 // Same address, same node
    33                 // There is a cycle in the list
    34                 return true;
    35             }
    36         }
    37     }
    38 };
  • 相关阅读:
    绝对定位和相对定位的内幕
    水平居中和垂直居中
    玩转html5<canvas>画图
    基本排序算法
    很好用的canvas
    IE浏览器存在的setAttribute bug
    js 高程 函数节流 throttle() 分析与优化
    js apply()、call() 使用参考
    js 高程 22.1.4 函数绑定 bind() 封装分析
    事件处理程序中 this 的指向
  • 原文地址:https://www.cnblogs.com/zhuli19901106/p/3518090.html
Copyright © 2011-2022 走看看