LeetCode19.删除链表的倒数第N个结点
代码注释解析
class Solution {
public:
int getLength(ListNode* head) {
int length = 0;
while (head) {
++length;
head = head->next;
}
return length;
}
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* newhead = new ListNode(0, head);
int length = getLength(head);
ListNode* cur = newhead;
for (int i = 1; i < length - n + 1; ++i) {
cur = cur->next;
}
ListNode* del = cur->next;
cur->next = cur->next->next;
ListNode* ans = newhead->next;
delete newhead;
delete del;
return ans;
}
};
|