160. 相交链表
复习知识点:本题属于思路题,主要考虑从起始点到交点的距离,或者使用从后向前进行寻找不相等的节点
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
// 首先可以想到从后向前遍历,碰到不相等的元素就退出,因此使用栈
stack<ListNode*> p1, p2;
for(ListNode* p = headA;p != nullptr;p = p -> next)
p1.push(p);
for(ListNode* q = headB;q != nullptr;q = q -> next)
p2.push(q);
ListNode* res = nullptr;
// 当两个栈非空并且顶端的元素相等的时候进行循环
for(;!p1.empty() && !p2.empty() && p1.top() == p2.top(); p1.pop(), p2.pop())
res = p1.top();
return res;
}
};
// 此题也可以利用两个链表分别从表头第二次经过相交节点的距离相同进行解答
// 即走到末尾的时候从另一个链表的头部开始继续向后,那么就会在相交位置相遇
169. 多数元素
复习知识点:本题与上面的题一样,属于思路类,可以通过排序,将位于一半位置的元素返回,该元素一定是多数元素。
class Solution {
public:
int majorityElement(vector<int>& nums) {
unordered_map<int, int>hash;
for(int num : nums)
{
++hash[num];
if(hash[num] > nums.size() / 2)
return num;
}
return 0;
}
};
// 本题也可以通过排序,中间位置上的元素一定是多数元素,直接返回即可
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* fast = head -> next;
ListNode* slow = head;
while(fast != slow)
{
// 如果其中一个走到末尾了说明没有环
if(fast == nullptr || fast -> next == nullptr)
return false;
fast = fast -> next -> next;
slow = slow -> next;
}
return true;
}
};
// 本题也可以通过将已经访问过的数据进行存储,如果该数字被访问两次,那么该链表成环