题目:
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.
Solution(1):
思路,找到这个点的前节点和后节点,连接起来。
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* temp = head;
int num = 0;
while(temp != NULL)
{
temp = temp->next;
num++;
}
int pre_num = num - n-1;
int del_num = num - n;
ListNode* pre_node = head;
ListNode* del_node =head;
if(n == num)
{
head = head->next;
return head;
}
while(pre_num--)
{
pre_node = pre_node->next;
}
while(del_num--)
{
del_node = del_node->next;
}
pre_node->next = del_node->next;
delete[] del_node;
return head;
}
Solution(2):
思路:定义双指针,保持距离为n,然后一个移到最后,另一个自然就是要删除节点的前一个节点了。
ListNode *removeNthFromEnd(ListNode *head, int n)
{
if(head == NULL || head->next == NULL)
return NULL;
ListNode * first_node = head;
ListNode *second_node = head;
for(int i=0;i<n;i++)
first_node = first_node->next;
if(first_node == NULL)//delete the head node
{
head = head->next;
return head;
}
while(first_node->next !=NULL)
{
first_node = first_node->next;
second_node = second_node->next;
}
second_node->next = second_node->next->next;
return head;
}