码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode]141. Linked List Cycle判断链表是否有环

时间:2018-06-26 11:07:35      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:etc   思路   src   OLE   without   code   AC   determine   技术分享   

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

 

题意:

给定一个链表,判断是否有环

 

思路:

快慢指针

若有环,则快慢指针一定会在某个节点相遇(此处省略证明)

技术分享图片

 

代码:

 1 public class Solution {
 2     public boolean hasCycle(ListNode head) {
 3         ListNode fast = head;
 4         ListNode slow = head;
 5         while(fast != null && fast.next != null){
 6             fast = fast.next.next;
 7             slow = slow.next;
 8             if(fast == slow) return true;
 9         }
10         return false;
11     }
12 }

 

[leetcode]141. Linked List Cycle判断链表是否有环

标签:etc   思路   src   OLE   without   code   AC   determine   技术分享   

原文地址:https://www.cnblogs.com/liuliu5151/p/9227172.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!