LeetCode 19. 删除链表的倒数第 N 个结点
作者:互联网
计算链表长度
/**
* 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 sum=0;
auto p=dummy;
while(p->next)sum++,p=p->next; //结点总数
p=dummy;
for(int i=0;i<sum-n;i++)p=p->next;
p->next=p->next->next;
return dummy->next;
}
};
//链表
标签:dummy,ListNode,val,19,next,链表,int,倒数第 来源: https://blog.csdn.net/m0_61794291/article/details/122633752