https://leetcode.cn/problems/remove-nth-node-from-end-of-list/
使用快慢指针,让nxt指针先向后移动N次
这样nxt指针和pre指针之间的间隔则为N
然后,nxt和pre同时向后移动,当nxt移动到链表的尾部,pre依然和它间隔为N,那么此时的pre就是链表的倒数第N个节点了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode* pre = head; ListNode* nxt = head; for(int i=0;i<n;i++) { nxt = nxt->next; } if(nxt == nullptr) { head = head->next; return head; }
while(nxt!=nullptr) { nxt = nxt->next; if(nxt == nullptr) { cout<<pre->val<<endl; pre->next = pre->next->next; return head; } pre = pre->next; } return head; } };
|