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

    分析

    难度 易

    来源

    https://leetcode.com/problems/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?

    解答

    Runtime: 0 ms, faster than 100.00% of Java online submissions for Linked List Cycle.

     1 package LeetCode;
     2 
     3 public class L141_LinkedListCycle {
     4     public boolean hasCycle(ListNode head) {
     5         //快慢指针。简单版本不需要返回循环开始节点
     6         if(head==null)
     7             return false;
     8         ListNode fast=head;
     9         ListNode slow=head;
    10         while(true){//fast.next不空则slow.next不空
    11           if( fast.next==null||fast.next.next==null)
    12               return false;
    13           else
    14           {
    15               fast=fast.next.next;
    16               slow=slow.next;
    17               if(slow==fast)
    18                   return true;
    19           }
    20         }
    21     }
    22     public static void main(String[] args){
    23         int[] nums={-21,10,17,8,4,26,5,35,33,-7,-16,27,-12,6,29,-12,5,9,20,14,14,2,13,-24,21,23,-21,5};
    24         ListNode head;
    25         ListNode pointer;
    26         pointer=head=new ListNode(nums[0]);
    27         for(int i=1;i<nums.length;i++)
    28         {
    29             pointer.next=new ListNode(nums[i]);
    30             pointer=pointer.next;
    31         }
    32         pointer=head;
    33         while(pointer!=null){
    34             System.out.print(pointer.val+"	");
    35             pointer=pointer.next;
    36         }
    37         L141_LinkedListCycle l141=new L141_LinkedListCycle();
    38         System.out.println(l141.hasCycle(head));
    39     }
    40 }

     

    博客园的编辑器没有CSDN的编辑器高大上啊
  • 相关阅读:
    django_4数据库3——admin
    django_4数据库2——表外键
    django_4:数据库1——django操作数据库
    django_4:数据库0——配置数据库
    django_3:url配置
    django_2:模板
    Python3安装mysql模块
    django_1:配置文件
    python:正则1
    POJChallengeRound2 Tree 【数学期望】
  • 原文地址:https://www.cnblogs.com/flowingfog/p/9923621.html
Copyright © 2011-2022 走看看