160. 相交链表
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if(headA == nullptr || headB == nullptr)
return nullptr;
ListNode* cur_a = headA;
ListNode* cur_b = headB;
while(cur_a != cur_b)
{
cur_a = (cur_a ? cur_a->next : headB);
cur_b = (cur_b ? cur_b->next : headA);
}
return cur_a;
}
};
169. 多数元素
class Solution {
public:
int majorityElement(vector<int>& nums) {
int n = nums.size();
map<int, int> hashmap;
for (int i = 0;i < n; i++)
{
if (hashmap.find(nums[i]) == hashmap.end())
{
hashmap[nums[i]] = 1;
}
else
{
hashmap[nums[i]]++;
}
if (hashmap[nums[i]] > n / 2)
{
return nums[i];
}
}
return 0;
}
};
206. 反转链表
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* prev = nullptr;
ListNode* curr = head;
while (curr) {
ListNode* next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
};