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

    题目:判断单链表是否有环,要求O(1)空间复杂度。题目链接

    利用快慢指针,开始两个指针均指向链表head,然后循环移动,慢指针移动1步,快指针则移动2步,如果链表有环则两个指针一定会相遇。代码如下:

     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 == NULL || head->next == NULL)return false;
    15         ListNode *fast = head, *low = head;
    16         while(fast != NULL && fast->next != NULL)
    17         {
    18             low  = low->next;
    19             fast = fast->next->next;
    20             if(low == fast)return true;
    21         }
    22         return false;
    23     }
    24 };

    当然还可以用倒转链表的方法来判断是否有环,沿着链表遍历,每次遍历把指针倒转,如果有环最后一定会回到head节点。不过这样会破坏链表结构 ,需要恢复。

     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 == NULL || head->next == NULL)return false;
    15         ListNode *p  = head->next, *pre = head;
    16         while(p)
    17         {
    18             if(p == head)return true;
    19             ListNode* tmp = p->next;
    20             p->next = pre;
    21             pre = p;
    22             p = tmp;
    23         }
    24         return false;
    25     }
    26 };

    【版权声明】转载请注明出处:http://www.cnblogs.com/TenosDoIt/p/3416670.html

  • 相关阅读:
    深入理解JVM(六)——类加载器原理
    深入理解JVM(五)——垃圾回收器
    深入理解JVM(四)——垃圾回收算法
    Let's Encrypt,免费好用的 HTTPS 证书
    开源框架(整理)
    【转】JS组件系列——Bootstrap组件福利篇:几款好用的组件推荐(二)
    C#开源项目大全
    window平台搭建Hudson服务器
    Git 常用命令
    Mongodb Windows 集群
  • 原文地址:https://www.cnblogs.com/TenosDoIt/p/3416670.html
Copyright © 2011-2022 走看看