zoukankan      html  css  js  c++  java
  • 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?

    注意,链表循环并不是尾指针和头指针相同,可能是在中间某一段形成一个环路,所以不能只判断元素和第一个元素是否存在重合

    先设置两个指针p_fast和p_slow。从头开始遍历链表,p_fast每次走两个节点,而p_slow每次走一个节点,若存在循环,这两个指针必定重合:

     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 false;
    13         
    14         ListNode *p_fast = head;
    15         ListNode *p_slow = head;
    16         
    17         do{
    18             p_slow = p_slow->next;
    19             if(p_fast != NULL)
    20                 p_fast = p_fast->next;
    21             if(p_fast != NULL)
    22                 p_fast = p_fast->next;
    23             else
    24                 return false;
    25         }while(p_fast != p_slow);
    26         
    27         return true;
    28         
    29     }
    30 };
  • 相关阅读:
    ajax代码及简单封装
    web开发中不同设备浏览器的区分
    JS实现带复选框的下拉菜单
    常用浏览器的编码设置
    PHP实现实现数字补零格式化
    Linux杂碎2/SHELL
    OS
    Linux sudoers
    代理缓存服务器squid
    es6
  • 原文地址:https://www.cnblogs.com/fanchangfa/p/4041629.html
Copyright © 2011-2022 走看看