标签: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 /** 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