Given a linked list, remove the nth node from the end of list and return its head.
For example,
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.
Note:
Given n will always be valid.
Try to do this in one pass.
题目本身比较简单,如果不考虑一次遍历的话,可以直接得出链表长度,然后一切都很简单。但是在一次遍历的情况下,我们无法得出这个链表的长度,此时我们可以用两个指针,第一个指针先走N步,如果此时1号指针指向空,即表明移除首元素。如果指向存在,这时引入2号指针,1号指针遍历完整个链表,同时2号指针也遍历链表,此时2号指针指向要移除元素的前一个元素,将其指向要移除元素的后一个元素即可
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if (!head->next) return NULL;
ListNode *pre = head, *cur = head;
for (int i = 0; i < n; ++i) cur = cur->next;
if (!cur) return head->next;
while (cur->next) {
cur = cur->next;
pre = pre->next;
}
pre->next = pre->next->next;
return head;
}
};