题意
方法
代码
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummy_node = new ListNode(1, head);
ListNode* tmp_node = head;
int N = 0;
while (tmp_node != nullptr) {
N++;
tmp_node = tmp_node->next;
}
n = N - n + 1;
cout << n << endl;
tmp_node = dummy_node;
ListNode* tmp_next = dummy_node;
int cnt = 0;
while (++cnt < n) {
tmp_next = tmp_next->next;
tmp_node = tmp_node->next;
}
tmp_next = tmp_node->next;
tmp_node->next = tmp_next->next;
return dummy_node->next;
}
总结
- 算上栈和双指针的解法, 比较妙的一题, 非常考验基础功力