19. Remove Nth Node From End of List

题目

https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/

想法

比较简单,就是记录着扫着的ptr之前n位的地址就可以了。

答案

一次AC

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
* 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;
}
};