1. 程式人生 > >141. Linked List Cycle 判斷鏈表中是否存在“環”

141. Linked List Cycle 判斷鏈表中是否存在“環”

turn ive time ast class 判斷 rom list blog

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 判斷鏈表中是否存在“環”