Linked List Cycle
发布日期:2021-11-22 02:48:40 浏览次数:1 分类:技术文章

本文共 810 字,大约阅读时间需要 2 分钟。

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

Follow up:

Can you solve it without using extra space?

题解:

问题:判断链表是否有环。
分析:利用快慢指针slow,fast
         slow指针每次走一步,fast指针每次走两步,倘若存在环,则slow和fast必定在某一时刻相遇。
         由于fast指针走的比slow快所以循环的时候只需要判断fast和fast->next不为空,判断fast->next是因为防止出现fast->NULL->next这种情况

code:

/** * Definition for singly-linked list. * class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {    public boolean hasCycle(ListNode head) {      if(head == null)		{			return false;		}		 ListNode slow,fast;	     slow = head;	     fast = head.next;	     while(fast!=null && fast.next!=null)	     {	    	 if(slow==fast) return true;	    	 slow = slow.next;	    	 fast = fast.next.next;	     }	      return false;    }}

转载地址:https://blog.csdn.net/zxdfc/article/details/46700461 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Binary Tree Preorder Traversal
下一篇:mybatis与spring整合

发表评论

最新留言

第一次来,支持一个
[***.219.124.196]2024年04月24日 21时14分43秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章