LeetCode: Remove Nth Node From End of List
Title:
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.
思路: 先让一个指针走n步,在让另一个指针一起向前。需要注意n的取值。有可能直接删除头指针,需要判断
class Solution {
public:
ListNode *removeNthFromEnd(ListNode *head, int n) {
if(head == NULL){
return head;
}
ListNode* dummy = new ListNode(0); // 处理删除头指针
dummy->next = head;
head = dummy;
ListNode* slow = head;
ListNode* fast = head;
for(int i = 0; i <n; i++){
fast = fast ->next;
}
while(fast->next != NULL){
fast = fast->next;
slow = slow->next;
}
ListNode* temp = slow->next;
slow ->next = slow->next->next;
delete temp;
return dummy->next;
}
};