环形链表 /** * 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) { setListNode * address; ListNode*
环形链表
/** * 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)