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
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.
代码
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了,还有点惊讶。。。
本文由 mmmwhy 创作,最后编辑时间为: Jun 6, 2018 at 02:55 pm