Leetcode141環形鏈表
1. 題目描述
2. 代碼實現
雙指針法實現
/*
* @Description:
* @version:
* @Author: sunshine
* @Github: https://subshine.github.io/
* @Email: [email protected]
* @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