jayati

Linked List Cycle II

Mar 9th, 2023
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.54 KB | None | 0 0
  1. /**
  2.  * Definition for singly-linked list.
  3.  * struct ListNode {
  4.  *     int val;
  5.  *     ListNode *next;
  6.  *     ListNode(int x) : val(x), next(NULL) {}
  7.  * };
  8.  */
  9. class Solution {
  10. public:
  11.     ListNode *detectCycle(ListNode *head) {
  12.         unordered_set<ListNode*>s;
  13.         ListNode* temp=head;
  14.         while(temp!=NULL){
  15.             if(s.find(temp)!=s.end()){
  16.                 return temp;
  17.             }else{
  18.                 s.insert(temp);
  19.                 temp=temp->next;
  20.             }
  21.         }
  22.         return NULL;
  23.        
  24.     }
  25. };
Advertisement
Add Comment
Please, Sign In to add comment