141. Linked List Cycle
解题思路:记录下每次head的地址,写到vector里,如果发现有重复,就返回true,如果到底了都没重复,就返回false。
(网上看搜索了一下,基本上千篇一律都是快慢指针的写法,很奇怪)
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ #include <iostream> #include <set> #include <algorithm> class Solution { public: bool hasCycle(ListNode *head) { vector<ListNode*> nodeSeen; vector<ListNode*>::iterator it; while(head!=NULL) { it=find(nodeSeen.begin(),nodeSeen.end(),head); if(it==nodeSeen.end())nodeSeen.push_back(head); else return true; head=head->next; } return false; } };