https://leetcode.cn/problems/SLwz0R/
这道题我们可以设一个哨兵位,然后把要遍历链表的结点指向该哨兵位。最后用for循环将指针指向要删除结点的前一个。
struct ListNode* removeNthFromEnd(struct ListNode* head, int n){
struct ListNode* dummy = malloc(sizeof(struct ListNode));
dummy->val = 0, dummy->next = head;
struct ListNode* cur = head;
int count = 0;
while(cur)
{
++count;
cur = cur->next;
}
cur = dummy;
for(int i =1 ; i< count - n +1 ; ++i)
{
cur = cur->next;
}
cur->next = cur->next->next;
cur = dummy->next;
free(dummy);
return cur;
}