oj141. Linked List Cycle

来源:互联网 发布:腾讯有网络币不 编辑:程序博客网 时间:2024/06/08 11:19

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;    }
答案思路:快慢指针

  1. 用两个指针,慢指针和快指针
  2. 慢指针每次走一步,快指针每次走两步
  3. 如果两个指针相遇,则有循环。
    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;    }


0 0
原创粉丝点击