019. Remove Nth Node From End of List

Given a linked list, remove the $n_{th}$ node from the end of list and return its head.

题目链接

19. Remove Nth Node From End of List

1
2
3
Given linked list: 1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5.

代码

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
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
//三指针
ListNode *pointa = head;//b前边的那个
ListNode *pointb = head;
ListNode *pointc = head;
if (head == NULL || n < 1) return head;
//前边指针先走n步
for (int i = 0; i < n; i++) {
pointc = pointc->next;
if (pointc == NULL&&i == n - 1) return head->next;
else if (pointc == NULL) return head;
}

while (pointc != NULL) {
pointc = pointc->next;
pointa = pointb;
pointb = pointb->next;
}

pointa->next = pointb->next;

return head;
}
};

一次就ac了,还有点惊讶。。。

019. Remove Nth Node From End of List

https://iii.run/archives/5a603f104d10.html

作者

mmmwhy

发布于

2018-06-06

更新于

2022-10-30

许可协议

评论