zoukankan      html  css  js  c++  java
  • Linked List Cycle II

    Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

    Follow up:
    Can you solve it without using extra space?

    题意

    判断一个链表是否有环,如果没有环,返回null。如果有环返回环开始的节点

    思路

    这里我用的是hash表来做,遍历链表,如果链表没有出现在hash表中,put到hash表中,如果在hash表中出现过,说明出现环,返回节点。遍历到链表最后,说明没有环,返回空

     1 import java.util.Hashtable;
     2 public class Solution {    
     3     public ListNode detectCycle(ListNode head) {        
     4         Hashtable<ListNode, ListNode> hashtable = new Hashtable<ListNode, ListNode>();
     5         while(head != null){
     6             ListNode temp = hashtable.get(head);
     7             if(temp == null){
     8                 hashtable.put(head, head);
     9                 head = head.next;
    10                 continue;
    11             }
    12             else{
    13                 return temp;
    14             }//else
    15         }//else
    16         
    17         return null;
    18     }
    19 }
  • 相关阅读:
    TP框架实现分页及条件查询
    tp框架连贯操作
    php查询
    php修改数据
    php增加数据处理
    php删除数据
    php怎么访问数据库
    php查询
    克隆及加载类
    php静态成员和接口
  • 原文地址:https://www.cnblogs.com/luckygxf/p/4216415.html
Copyright © 2011-2022 走看看