力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

我们首先通过n的值来找到需要删去结点的前一个结点的值 target=count-n;count是结点总数,然而我们的头结点向后移动target-1次就可以移动到需要删除节点的前一个结点,然后将该结点cur->next=cur->next->next;就可以很容易的删除该结点。
注意:可能需要我们删除的结点是第一个结点,那么我们只需要返回头结点的下一位就可以了,return head->next;
- /**
- * 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)
- {
- if(head==nullptr) return nullptr;
- ListNode* cur=head;
- int count=0;
- while(cur)
- {
- count++;
- cur=cur->next;
- }
- if(n>count) return nullptr;
- cur=head;
- int target=count-n;
- cout<<"target:"<
- // 如果target==0 那么删去的就是第一个结点
- if(target==0) return head->next;
- while(--target)
- {
- cur=cur->next;
- }
- cur->next=cur->next->next;
- return head;
- }
- };