Leetcode 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?

这道题用来判断链表中是否有循环,最开始我想的是遍历链表,同时用一个list保存遍历过的节点,然后查看该节点的next节点是否存在于list中,若存在则说明该链表存在循环。

但由于是n2的时间代价,提示我超时间。

 1 package Linked.List.Cycle;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 
 6 public class LinkedListCycle {
 7 public boolean hasCycle(ListNode head) {
 8     int len=0;
 9     List<ListNode> list=new ArrayList<ListNode>();
10     ListNode index=head; 
11     if(index==null) return false;
12     if(index.next==index) return true;
13     boolean isCycle=false;
14     while(index!=null){
15         list.add(index);
16         ListNode obj=index.next;
17         if(list.contains(obj))
18         {
19             isCycle=true;
20             break;
21         }
22         index=index.next;
23     }
24     if(isCycle)
25         return true;
26     else return false;
27     
28     }
29 }

后来查看人家的算法思想,发现快慢指针在链表中是个很好用的工具,不仅可以轻松得到中间节点,还可以解决相遇问题

 1 package Linked.List.Cycle;
 2 
 3 public class LinkedListCycle1 {
 4      public boolean hasCycle(ListNode head) {
 5         ListNode fast=head;
 6         ListNode slow=head;
 7         boolean isCycle=false;
 8         ListNode index=head; 
 9         if(index==null) return false;
10         if(index.next==index) return true;
11         if(index.next.next==index) return true;
12         if(index.next==null) return false;
13         while(fast!=null&&fast.next!=null){
14             slow=slow.next;
15             fast=fast.next.next;
16             if(slow==fast)
17             {
18                 return true;
19             }
20         }
21         return false;
22      }
23 }

 

转载于:https://www.cnblogs.com/criseRabbit/p/4111793.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值