p121 单链表中圆环的开始节点(leetcode 142)

一:解题思路

方法一:使用一个辅助集合。Time:O(n),Space:O(n)

方法二:快慢指针法。Time:O(n),Space:O(1)

二:完整代码示例 (C++版和Java版)

方法一C++:

class Solution {
public:
    ListNode *detectCycle(ListNode *head) 
    {
        set<ListNode*> s;
        for (ListNode* p = head; p != NULL; p = p->next)
        {
            if (s.count(p) != 0) return p;
            s.insert(p);
        }

        return NULL;
    }
};

方法一Java:

public class Solution {
        public ListNode detectCycle(ListNode head) 
        {
               Set<ListNode> set=new HashSet<>();
               for(ListNode p=head;p!=null;p=p.next)
               {
                   if(set.contains(p)) return p;
                   set.add(p);
               }
               
               return null;
        }
    }

方法二C++:

class Solution {
public:
    ListNode *detectCycle(ListNode *head) 
    {
        ListNode* fast = head;
        ListNode* slow = head;
        while (fast != NULL && fast->next != NULL)
        {
            fast = fast->next->next;
            slow = slow->next;

            if (fast == slow)
            {
                for (ListNode* p = head; p != slow; p = p->next, slow = slow->next);
                return slow;
            }
        }

        return NULL;
    }
};

方法二Java:

public class Solution {
        public ListNode detectCycle(ListNode head) 
        {
              ListNode fast=head;
              ListNode slow=head;
              while(fast!=null && fast.next!=null)
              {
                  fast=fast.next.next;
                  slow=slow.next;
                  
                  if(fast==slow)
                  {
                      for(ListNode p=head;p!=slow;p=p.next,slow=slow.next);
                      return slow;
                  }
              }
              
              return null;
        }
    }
posted @ 2020-04-13 20:38  repinkply  阅读(205)  评论(0)    收藏  举报