LeetCode 环形链表

版权声明:欢迎提问:[email protected] https://blog.csdn.net/include_heqile/article/details/82796447

https://leetcode-cn.com/problems/linked-list-cycle/description/

我的解决方案:

class Solution {
	//这是剑指offer上的一道题目,最经典的判断链表是否为环状的方法就是设置两个指针,一个指针每次走一步,另一个指针每次走两步,
	//如果走的快的指针和走的慢的指针相等了,则说明链表中存在环,否则没有环
    public boolean hasCycle(ListNode head) {
        if(head==null) return false;
    	ListNode head1 = head;
    	ListNode head2 = head;
    	if(head.next==null)
    		return false;
    	else if(head.next==head)
    		return true;
        while(head1!=null&&head2!=null) {
        	head1=head1.next;
        	if(head2.next!=null)
        		head2=head2.next.next;
        	else
        		return false;
        	if(head1==head2)
        		return true;
        }
    	return false;     
    }
} 

猜你喜欢

转载自blog.csdn.net/include_heqile/article/details/82796447
今日推荐