[] Data structures and algorithms (ii) list

Circular linked list

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool hasCycle(ListNode *head) {
        set<ListNode *> address; 
        ListNode* pos=head;
        while(true){
               if(pos==NULL){
                   return false;
               }
               if(address.count(pos)==1){
                   return true;
               }else {
                  address.insert(pos);                   
               }
                   
               pos=pos->next;
               
               
           }
        return true;
                
    }
};

  

Highlights:

c ++ STL function Set associative containers support efficient keyword search and access

set.insert(1);

set.count(1)

count () is used to find a certain number of times set in key emerging. This function is not very practical in the set, as a key value may appear only in set 0 or 1, so that it becomes a judgment whether there is a key value in the set before.

RB is set underlying implementations tree (i.e., red-black tree)

 

Guess you like

Origin www.cnblogs.com/jiwen/p/11372643.html