oj141. Linked List Cycle

    xiaoxiao2021-04-16  55

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

    翻译:给定一个链表,确定它是否有一个循环。

    超时思路:

    新建一个list来装链表节点,若新节点指向的下一个节点已经存在list中,则返回真

    public boolean hasCycle(ListNode head) { List<ListNode> l = new ArrayList<ListNode>(); l.add(head); if(head == null) return false; ListNode nextNode = head.next; while(nextNode!= null){ if(l.contains(nextNode)) return true; l.add(nextNode); nextNode = nextNode.next; } return false; }答案思路:快慢指针

    用两个指针,慢指针和快指针慢指针每次走一步,快指针每次走两步如果两个指针相遇,则有循环。public boolean hasCycle(ListNode head) { if(head == null) return false; ListNode walker = head; ListNode runner = head; while(runner.next != null && runner.next.next != null){//快指针走的快,这里要判断快指针是否为空。 walker = walker.next; runner = runner.next.next; if(walker == runner) return true; } return false; }

    转载请注明原文地址: https://ju.6miu.com/read-672748.html

    最新回复(0)