题目链接:
题解:
两个 $p,q$ 指针均指向头, 然后 $q$ 先往前走 $n$ 步, 然后 $p,q$ 一起走, 直到 $q$ 走到底, 此时 $p$ 的位置即倒数第 $n$ 个的位置.
AC 代码:
- static const auto io_sync_off = []()
- {
- std::iOS::sync_with_stdio(0);
- std::cin.tie(0);
- std::cout.tie(0);
- return nullptr;
- }();
- struct Solution
- {
- ListNode* removeNthFromEnd(ListNode* head, int n)
- {
- ListNode* q=head;
- ListNode* p=head;
- while(n--) q=q->next;
- while(q!=NULL && q->next!=NULL) p=p->next, q=q->next;
- if(q==NULL) head=p->next;
- else p->next=p->next->next;
- return head;
- }
- };
来源: http://www.bubuko.com/infodetail-2992172.html