题目描述:
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.
分析:
链表问题一般思路是双指针方法,让第一个指针先走N-1步,然后第二个指针从头开始和第一个指针同时走,第一个指针到达链表尾部时,第二个指针指向要删除的节点。
需要注意的是,考虑几种特殊情况:1、空链表。2、链表不足N项。3、链表正好N项(此时需要删除链表头)。
还需特别注意第一个指针需要领先几步,可以举例来实验
代码实现:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
if(NULL == head)
{
return NULL;
}
int cnt = n;
struct ListNode* fast = head;
struct ListNode* slow = head;
struct ListNode* pre = NULL;
while(--cnt)
{
fast = fast->next;
if(fast == NULL)
{
return NULL;
}
}
if(fast->next == NULL)
{
return head->next;
}
while(fast->next != NULL)
{
pre = slow;
fast = fast->next;
slow = slow->next;
}
pre->next = slow->next;
return head;
}