LeetCode 19 . 删除链表的倒数第N个节点
19 . 删除链表的倒数第N个节点
class Solution {
public:
ListNode *removeNthFromEnd(ListNode *head, int n) {
ListNode *_Head = new ListNode(0);
_Head->next = head;
ListNode *fast = _Head;
int walk = n;
while (walk) {
fast = fast->next;
walk--;
}
ListNode *slow = _Head;
while (fast->next != nullptr) {
fast =fast->next;
slow = slow->next;
}
// 需要删除 s.next
ListNode *del = slow->next;
slow->next = slow->next->next;
delete del;
del = nullptr;
return _Head->next;
}
};
LeetCode 面试题 02.07. 链表相交
面试题 02.07. 链表相交
哈希表查找,无序集合 底层是 哈希表,查找视为 O(1)
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if (headA == nullptr || headB == nullptr)
return nullptr;
ListNode *a = headA;
ListNode *b = headB;
set<ListNode*> set_list;
while (a != nullptr) {
set_list.insert(a);
a = a->next;
}
ListNode *res = nullptr;
while (b != nullptr) {
if (set_list.find(b) != set_list.end()) {
res = b;
break;
}
b = b->next;
}
return res;
}
画图进阶
headA : a b c d f
headB :y z d f
A + B : a b c d f y z d f
B + A : y z d f a b c d f
数学逻辑为先,还是厉害,还得多关联思考。
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if (headA == nullptr || headB == nullptr)
return nullptr;
ListNode *a = headA;
ListNode *b = headB;
while (a != b) {
a = (a == nullptr) ? headB : a->next;
b = (b == nullptr) ? headA : b->next;
}
return a;
}
};
LeetCode 142 . 环形链表 II
142 . 环形链表 II
需要二刷理解,数学推理一下。
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode *slow = head, *fast = head;
while (fast != nullptr) {
slow = slow->next;
if (fast->next == nullptr) {
return nullptr;
}
fast = fast->next->next;
if (fast == slow) {
ListNode *ptr = head;
while (ptr != slow) {
ptr = ptr->next;
slow = slow->next;
}
return ptr;
}
}
return nullptr;
}
};
906

被折叠的 条评论
为什么被折叠?



