思路:
先计算链表的长度cnt,然后找到第cnt - n个元素(指针跳cnt - n - 1次),把当前元素的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) {
auto dummy = new ListNode (-1);
dummy->next = head;
int cnt = 0;
auto p=dummy;
while(p){
cnt++;
p=p->next;
}
p = dummy;
for(int i = 0; i < cnt - n - 1; i++) p = p->next;
p->next = p->next->next;
return dummy->next;
}
};
评论区