Given a linked list, remove the n-th node from the end of list and return its head.
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.
Follow up:
Could you do this in one pass? 你能一遍过吗(笑
AC代码
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if (head->next == NULL) return NULL;
ListNode *head_cp = head, *shadow = head, *pre_shadow = head;
n--;
while (n--) head_cp = head_cp->next;
while (head_cp->next != NULL) {
head_cp = head_cp->next;
pre_shadow = shadow;
shadow = shadow->next;
}
if (pre_shadow != shadow) {
pre_shadow->next = shadow->next;
delete shadow;
}
else {
ListNode* t = shadow->next;
delete shadow;
return t;
}
return head;
}
};
总结
无
网友评论