/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *dummy = new ListNode(0, head);
ListNode *slow = dummy, *fast = head;
while(n>0){
fast = fast->next;
n--;
}
while(fast){
slow = slow->next;
fast = fast->next;
}
slow->next = slow->next->next;
return dummy->next;
}
};
22)链表中环的入口节点
class Solution{
public:
ListNode *detectCycle(ListNode *head){
ListNode* slow = head, *fast = head;
while(fast){
slow = slow->next;
if(fast->next==nullptr) return nullptr;
fast = fast->next->next;
if(slow == fast){
ListNode* pre = head;
while(pre != slow){
pre = pre->next;
slow = slow->next;
}
return slow;
}
}
return nullptr;
}
};
23)两个链表的第一个重合节点
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if(headA==nullptr || headB==nullptr) return nullptr;
ListNode *pA = headA, *pB = headB;
while(pA != pB){
pA = pA==nullptr ? headB : pA->next;
pB = pB==nullptr ? headA : pB->next;
}
return pA;
}
};