题目形容
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。应用一趟扫描实现。
题目作者:力扣 (LeetCode)
链接:https://leetcode-cn.com/leetb…
题解作者:WildDuck
题目剖析
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
typedef struct ListNode* ListNode_pointer;
struct ListNode* removeNthFromEnd(struct ListNode* head, int n)
{
// 两个指针构建一个窗口套住固定间隔
ListNode_pointer fast = head;
ListNode_pointer slow = head;
for(int i=0;i<n;i++)
{fast = fast -> next;}
while(fast != NULL && fast->next != NULL)
{
fast = fast -> next;
slow = slow -> next;
}
if(fast == NULL)// 对仅含一个元素的链表非凡解决
{
head = head -> next;
free(slow);
}
else
{
ListNode_pointer free_p = slow->next;
slow -> next = slow->next->next;
free(free_p);
}
return head;
}
窗口套住固定间隔