flowingfog

偶尔刷题

  博客园  :: 首页  :: 新随笔  :: 联系 ::  :: 管理

分析

难度 易

来源

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+"\t");
35             pointer=pointer.next;
36         }
37         L141_LinkedListCycle l141=new L141_LinkedListCycle();
38         System.out.println(l141.hasCycle(head));
39     }
40 }

 

 

posted on 2018-11-07 16:57  flowingfog  阅读(34)  评论(0编辑  收藏