Leetcode141环形链表
1. 题目描述
2. 代码实现
双指针法实现
/*
* @Description:
* @version:
* @Author: sunshine
* @Github: https://subshine.github.io/
* @Email: 2182216077@ncepu.edu.cn
* @Date: 2020-04-20 22:23:03
* @LastEditTime: 2020-04-20 22:44:24
*/
/*
* @lc app=leetcode.cn id=141 lang=cpp
*
* [141] 环形链表
*/
// @lc code=start
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
//为啥pos值没有传进来,事实上head是pos后的链表,主要问题是判断此链表是否是环形链表
//双指针法:如果是环形链表,则两个指针肯定要相遇,否则不会相遇
class Solution {
public:
bool hasCycle(ListNode* head) {
ListNode* faster=head;
ListNode* slower=head;
if(head==nullptr) {
return false;
}
while(faster!=nullptr&&faster->next!=nullptr) {
faster = faster->next->next;
slower = slower->next;
if(faster==slower) {
return true;
}
}
return false;
}
};
// @lc code=end