题目:
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.
链接:Remove Nth Node From End of List
解法:题目要求一次遍历删除,因此设置两个指针,当第一个指针移动n次后第二个指针开始移动,则当第一个指针移动到链表尾时,第二个指针指向需要删除的节点,注意删除的节点是头结点的情况。时间O(n)
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
int cnt = 0;
ListNode* p1 = head;
ListNode* p2 = NULL;
while (p1) {
cnt++;
p1 = p1->next;
if (cnt == n + 1) p2 = head;
else if (cnt > n + 1) p2 = p2->next;
}
if (p2) {
p1 = p2->next;
p2->next = p1->next;
p1->next = NULL;
delete(p1);
} else {
p2 = head;
head = head->next;
delete(p2);
}
return head;
}
};
Runtime: 6 ms