Datawhale-LeetCode编程实践组队学习Task13

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;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_43627017/article/details/113157721