leetcode 141
要求:判断一个链表是否是循环链表
思路:给两个指针,一个跑的快,一个跑得慢,如果快的和慢的能相遇,则是循环链表,否则不是
#include<cstdlib>
#include<iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode *slow=head;
ListNode *fast=head->next;
if(slow==NULL||fast==NULL) return false;
while(slow!=fast){
if(fast==NULL||fast->next==NULL) return false;
slow=slow->next;
fast=fast->next->next;
}
return true;
}
};
int main(){
ListNode node1(1);
ListNode node2(1);
ListNode node3(3);
ListNode node4(4);
ListNode node5(4);
ListNode node6(4);
node1.next=&node2;
node2.next=&node3;
node3.next=&node4;
node4.next=&node5;
node5.next=&node6;
node6.next=&node1;
Solution s;
cout<<s.hasCycle(&node1);
return 0;
}