环形链表
/** * 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; } };
要点:
c++ STL 函数 Set 关联容器支持高效的关键字查找和访问
set.insert(1);
set.count(1)
count() 用来查找set中某个某个键值出现的次数。这个函数在set并不是很实用,因为一个键值在set只可能出现0或1次,这样就变成了判断某一键值是否在set出现过了。
set底层实现方式为RB树(即红黑树)