19. Remove Nth Node From End of List Posted on 2017-08-17 | Edited on 2018-07-10 | In OJ , LeetCode | 题目https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/ 想法比较简单,就是记录着扫着的ptr之前n位的地址就可以了。 答案一次AC 1234567891011121314151617181920212223242526272829303132/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode* target = head; ListNode* ptr = head; for (int i = 0; i < n; i++) { ptr = ptr->next; } if (ptr == NULL) { ListNode* tmp = head; head = head->next; free(tmp); return head; } while(ptr->next != NULL) { ptr = ptr->next; target = target->next; } ListNode* tmp = target->next; target->next = tmp->next; free(tmp); return head; }};