计算链表长度
/**
* 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 {
int getLength(ListNode* head) {
int len = 0;
ListNode* cur = head;
while(cur) {
len += 1;
cur = cur->next;
}
return len;
}
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
int len = getLength(head);
ListNode* dummy = new ListNode(0, head);
ListNode* cur = dummy;
for (int i = 0; i < len - n; i++) {
cur = cur->next;
}
cur->next = cur->next->next;
ListNode* ans = dummy->next;
delete dummy;
return ans;
}
};