141. Linked List Cycle 判断链表中是否存在“环”

Posted lvbbg

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了141. Linked List Cycle 判断链表中是否存在“环”相关的知识,希望对你有一定的参考价值。

141. Linked List Cycle


 

 

Given a singly linked list, determine if it is a palindrome.

Follow up:
Could you do it in O(n) time and O(1) space?

快慢指针

  1. 快指针从head+1出发,慢指针从head出发, 当快能够追上慢,说明有环
  2. 需判断头结点/头指针为空的清情形
 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     bool hasCycle(ListNode *head) {
12         if (head == nullptr || head->next == nullptr)
13             return 0;
14         
15         ListNode* pSlow = head;
16         ListNode* pFast = head->next;
17         
18         while (pFast != nullptr && pSlow != nullptr)
19         {
20             if (pFast == pSlow)
21                 return 1;
22             
23             pSlow = pSlow->next;
24             pFast = pFast->next;
25             
26             if (pFast != nullptr)
27                 pFast = pFast->next;
28         }
29         return 0;
30     }
31 };

 

以上是关于141. Linked List Cycle 判断链表中是否存在“环”的主要内容,如果未能解决你的问题,请参考以下文章

141. Linked List Cycle

[leetcode]141. Linked List Cycle判断链表是否有环

141. Linked List Cycle

141. Linked List Cycle

LeetCode 141. Linked List Cycle(判断链表是否有环)

141. Linked List Cycle 判断链表是否有环