Title Description
Given a list, delete list reciprocal of n nodes, and returns to the head node list.
Thinking
- First traverse the list record length, before re-iterate to delete a position, delete skip bit. This method requires to traverse twice
- Traversing double pointer, a pointer pointing to the start point A, when the pointer n + 1 step A proceeds, pointer B point to the starting point of beginning, when it reaches the end A, B happens to be a point before the deletion node
Code
method one:
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if(head == NULL)
return NULL;
ListNode* cur = head;
int count = 0;
while(cur!= NULL)
{
count++;
cur = cur->next;
}
if(n == count)
return head->next;
if(n == 0)
return head;
cur = head;
int i = 0;
while(i < count-n-1)
{
cur = cur->next;
i++;
}
if(cur->next->next)
{
cur->next = cur->next->next;
}
else
{
cur ->next = NULL;
}
return head;
}
};
Method Two:
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummy = new ListNode(NULL);
dummy->next = head; //添加头节点,便于操作
ListNode* slow=dummy,* fast=dummy;
int distance=0;
while(fast->next){
if(distance<n){
fast=fast->next;
distance++;
}else{
fast=fast->next;
slow=slow->next;
}
}
slow->next=slow->next->next;
return dummy->next;
}
};