Remove Nth Node From End of List
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.
例如:
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.
说明:
n 都是合法的。
只遍历一次。
分析:
维护两个指针,第一个指针 p 先从表头移动 n+1 个位置,然后第二个指针 pre 跟随移动,当 p 到达表尾时,pre 指向要删除节点的前一个位置,删除第 n 个节点即可。
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if(!head || n < 0)//空
{
return head;
}
ListNode *pre = head, *p = head;
while(p && n-- >= 0)//先移动n+1个位置
{
p = p->next;
}
if(n >= 0)//删除的是头节点
{
head = head->next;
delete p;
return head;
}
while(p)//pre指向要删节点的前一个节点
{
pre = pre->next;
p = p->next;
}
p = pre->next;
pre->next = p->next; //删除节点
delete p;
return head;
}
};