Acy夕拾算法 Week1_day2
206. 反转链表
/*整理思路:
·采用 双+1指针,cur指向当前,temp存储(指向)当前next的位置,cur_pre存储(指向)当前cur 逆序应该的next位置
·返回 由于循环后,当前指向了下一个,所以要返回cur_pre
错误点:
·盲目创建虚拟头结点:并不需要虚结点ListNode* d_head = new ListNode(0);–这样尾会有答案外多余的0
·指针在定义时,不能连着写,一个指针一个ListNode*; 建立与赋值不能分开写;
·没有考虑原 头指针 如何结尾,即原 头指针的next应为nullptr
·思路错误:采用双指针,没有考虑到指针的next改变后,无法继续向前遍历;应采用三指针
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head == nullptr) return head;
ListNode* cur = head;//不能连着写
ListNode* cur_pre = nullptr;//cur_next容易混淆
ListNode* temp;
// cur = d_head, cur_pre = nullptr;//不能分开写
while(cur != nullptr)// while(cur->next != nullptr)
{
temp = cur->next;
cur->next = cur_pre;
cur_pre = cur;
cur = temp;
// temp = cur;//能通过,但是没有发挥名字的意思
// cur = cur->next;
// temp->next = cur_pre;
// cur_pre = temp;
}
head = cur_pre;//
delete cur, temp, cur_pre;
return head;//规范写//return cur_pre;
}
};
141. 环形链表
方法一:龟兔赛跑-快慢指针
/*
整理思路:
·龟兔赛跑算法:兔子快,乌龟慢;
·兔子原本应该永远在乌龟前,但由于链表中有环,某一时刻二者相遇。
··两指针,快在head->next,慢在head,快的一次移动2步,慢的一次1步;
··环:快慢相遇
··非环:快到nullptr
··要思考循环条件;思考无结点、一个结点的情况;
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head == nullptr || head->next == nullptr) return false;
ListNode* fast = head->next;
ListNode* slow = head;
// bool res = true;
while(fast != slow)//循环条件
{
if((fast == nullptr) || (fast->next == nullptr))//确保不空,能访问到
return false;//直接返回。如果用res,后面的fast = fast->next->next;还需要再判断是否nullptr
fast = fast->next->next;
slow = slow->next;
}
return true;
}
};
方法二:哈希表
集合 | 排序 | 重复 |
---|---|---|
set | 自动排序 | 无 |
multiset | 自动排序 | 有 |
unordered_set | 无序 | 无 |
选unordered_set,无序不重复
/*
整理思路:
·哈希表,判断节点是否被遍历过;用哈希表存储访问过的节点;
··unordered_set无序不重复,放入地址
··.conunt()看哈希表里有没有,有1,没0;.insert()插入
*/
public:
bool hasCycle(ListNode *head) {
unordered_set<ListNode*> uset;
while(head != nullptr)
{
if(uset.count(head))
return true;
uset.insert(head);
head = head->next;
}
return false;
}
};
21. 合并两个有序链表
/*
整理思路:
·用虚拟头节点链接节点,遍历时更改链1链2的头指针
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
ListNode* d_head = new ListNode(0);
// d_head->next = nullptr;
ListNode* cur = d_head;
while(list1 != nullptr && list2 != nullptr)
{
if(list1->val < list2->val)
{
cur->next = list1;
list1 = list1->next;
}
else
{
cur->next = list2;
list2 = list2->next;
}
cur = cur->next;
}
cur->next = list1 != nullptr? list1 : list2;//代码随想录;list1不是空,就把list1接上
return d_head->next;
}
};