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 };

 

posted @ 2017-10-24 18:58  绿宝宝怪  阅读(166)  评论(0编辑  收藏  举报
#site_nav_under,#ad_under_post_holder,#under_post_news,#google_ad_c2,#under_post_kb{ width:0; height:0; display:none; overflow:hidden; }