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

    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?

    这道题要用双指针,但我想试一下投机取巧的办法行不行,果然A了

     1 /**
     2  * Definition for singly-linked list.
     3  * class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) {
     7  *         val = x;
     8  *         next = null;
     9  *     }
    10  * }
    11  */
    12 public class Solution {
    13     public boolean hasCycle(ListNode head) {
    14         if(null == head)
    15             return false;
    16         ListNode point = head;
    17         while(null != point){
    18             if(point.val != Integer.MIN_VALUE)
    19                 point.val = Integer.MIN_VALUE;
    20             else
    21                 return true;
    22                 point = point.next;
    23         }        
    24         return false;
    25     }
    26 }

     双指针,一个走一步一个走两步,有环两个一定会相遇

     1 /**
     2  * Definition for singly-linked list.
     3  * class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) {
     7  *         val = x;
     8  *         next = null;
     9  *     }
    10  * }
    11  */
    12 public class Solution {
    13     public boolean hasCycle(ListNode head) {
    14         if(null == head)
    15             return false;
    16         ListNode slow = head;
    17         ListNode fast = head;
    18         while(fast != null && fast.next != null){
    19             slow = slow.next;
    20             fast = fast.next.next;
    21             if(slow == fast)
    22                 return true;
    23         }
    24         return false;
    25     }
    26 }
  • 相关阅读:
    python 学习笔记(二)
    python list的简单应用
    linux命令--------系统自带vi/vim命令教程
    归并排序的时间复杂度分析
    webapplication发布
    安装windows phone 7
    部署webservice到远程服务器
    SQLserver2005描述对数据的调用
    11.python-过滤器(filter)
    10.python-映射函数(map)
  • 原文地址:https://www.cnblogs.com/luckygxf/p/4111376.html
Copyright © 2011-2022 走看看