码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-10-24 20:49:28      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:class   init   bool   说明   cycle   null   term   ace   struct   

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 判断链表中是否存在“环”

标签:class   init   bool   说明   cycle   null   term   ace   struct   

原文地址:http://www.cnblogs.com/xumh/p/7725198.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!