判断一个链表中是否存在环

2017-09-19  本文已影响0人  光影墨辰

链表节点:

class ListNode {
    int val;
    ListNode next = null;
    public ListNode(int a){
        this.val = a;
    }
}

判断由上诉节点组成的链表中是否存在环

思路:

用两个指针(cur1和cur2)指向链表的头部,一个指针每次向后走一个节点,另一个指针每次向后走两个节点,如果有环,则cur1和cur2必然在某个时候相等。
代码实现:

public static boolean isCycle(ListNode head){
        if(head == null || head.next == null){
            return false;
        }
        ListNode cur1 = head;
        ListNode cur2 = head;
        while(cur1.next != null && cur2.next != null){
            cur1 = cur1.next;
            cur2 = cur2.next;
            if(cur2.next == null){
                break;
            }
            cur2 = cur2.next;
            if(cur1 == cur2){
                return true;
            }
        }
        return false;
    }
上一篇 下一篇

猜你喜欢

热点阅读