class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
auto dummy = new ListNode(0, head);
auto fast = dummy, slow = dummy;
for(int i = 0; i < n && fast != nullptr; i++) {
fast = fast->next;
}
fast = fast->next;
while(fast != nullptr) {
fast = fast->next;
slow = slow->next;
}
auto deleteNode = slow->next;
slow->next = deleteNode->next;
delete deleteNode;
auto res = dummy->next;
delete dummy;
return res;
}
};
LeetCode 160.相交链表
难度:简单
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
auto nodeA = headA, nodeB = headB;
while(nodeA != nodeB) {
nodeA = nodeA ? nodeA->next : headB;
nodeB = nodeB ? nodeB->next : headA;
}
return nodeA;
}
};
LeetCode 142.环形链表II
难度:中等
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
auto fast = head, slow = head;
do {
if(fast == nullptr || fast->next == nullptr) {
return nullptr;
}
fast = fast->next->next;
slow = slow->next;
} while(fast != slow);
fast = head;
while(fast != slow) {
fast = fast->next;
slow = slow->next;
}
return slow;
}
};