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 };
  • 相关阅读:
    innodb的存储结构
    使用zabbix邮件发送报表
    如何使用yum下载rpm包
    redis cluster节点管理测试
    redis迁移工具-redis-migrate-tool使用测试
    redis客户端连接异常
    redis sentinel基本命令与参数
    [转]redis-cli的一些有趣也很有用的功能
    [转]为什么使用 Redis及其产品定位
    Redis多机常用架构-cluster
  • 原文地址:https://www.cnblogs.com/zhuli19901106/p/3518090.html
Copyright © 2011-2022 走看看