这一题是容器的妙用,很巧妙的使用了vector来装载链表节点,从而进行判断这个节点是否转进vector里了。
一开始我陷入了思维误区,认为要使用循环来寻找重复节点、没有想到怎么存储这些节点、我惯性的认为节点就得用链表存,但是链表存起来若有循环该如何结束呢。
随后想到使用vector,只需要存储这个节点就可以了,这个节点所连接的的链表就算有循环也是地址的指向循环,不会出现无限扩张的内存占用。
同时在存一个节点之前查询vector里面是否已经存在了这个节点,若出现了第一个重复节点则返回,若不出现则继续向vector内存储,直到出现重复或遍历完链表。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
#include <cstddef>
#include <vector>
#include <iostream>
class Solution {
public:
bool hasCycle(ListNode *head) {
using namespace std ;
//遍历可能循环链表,当节点出现两次break,当遍历完返回true
ListNode *r;
vector<ListNode *> l;
r=head;
while (r!=nullptr) {
auto it = find(l.begin(),l.end(),r);
if (it != l.end()) {
return true;
}else {
l.push_back(r);
}
r=r->next;
}
return false;
}
};