Do it with map(C++)


  • -4
    P

    /**

    • Definition for singly-linked list.
    • struct ListNode {
    • int val;
      
    • ListNode *next;
      
    • ListNode(int x) : val(x), next(NULL) {}
      
    • };
      /
      //将指针存入哈希表可以解决这个问题
      class Solution {
      public:
      ListNode detectCycle(ListNode head) {
      ListNode
      ptr=head;
      int i=0;
      if(head==NULL)
      return NULL;
      //ListNode
      p=head;
      map<ListNode
      ,int> mymap;
      while(ptr)
      {
      if(mymap.find(ptr)==mymap.end())
      {
      mymap[ptr]=i;
      i++;
      ptr=ptr->next;
      }
      else
      {
      return ptr;
      }
      }
      return NULL;
      }
      };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.