136. 只出现一次的数字
class Solution {
public:
int singleNumber(vector<int>& nums) {
int ans = 0;
for (int n : nums)
{
ans ^= n;
}
return ans;
}
};
141. 环形链表
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
if (head == nullptr || head->next == nullptr)
return false;
ListNode *quick, *slow;
quick = head->next;
slow = head;
while (quick != slow)
{
if (quick == nullptr || quick->next == nullptr)
return false;
quick = quick->next->next;
slow = slow->next;
}
return true;
}
};
142. 环形链表 II
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if (head == nullptr || head->next == nullptr)
return nullptr;
ListNode *slow, *quick;
slow = head;
quick = head->next;
while (quick != slow)
{
if (quick == nullptr || quick->next == nullptr)
return nullptr;
slow = slow->next;
quick = quick->next->next;
}
int cnt = 0;
do
{
quick = quick->next->next;
slow = slow->next;
cnt++;
}while (quick != slow);
quick = head;
slow = head;
while (cnt != 0)
{
quick = quick->next;
cnt--;
}
while (quick != slow)
{
quick = quick->next;
slow = slow->next;
}
return quick;
}
};