/** * struct ListNode { * int val; * struct ListNode *next; * }; */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * @author Senky * @date 2023.04.18 * @par url https://www.nowcoder.com/creation/manager/content/584337070?type=column&status=-1 * @brief * @param head ListNode类 * @param n int整型 * @return ListNode类 */ struct ListNode* removeNthFromEnd(struct ListNode* head, int n ) { // write code here struct ListNode* first =head; struct ListNode* second =head; struct ListNode* result =head; struct ListNode* pre = NULL; int count = 0; while(first) { count++; first = first->next; } if(1 == count) result = NULL; if(count < n) result = NULL; if(count == n) result = head->next; for(int i = 0; i < count - n; i++) { pre = second; second = second->next; } if(pre) pre->next = second->next; return result; }
Algorithm:
删除倒数第k个结点,首先找到正数第n-k+1结点,在循环的时候用一个指针记录其前驱,找到第n-k+1个结点时也找到了第n-k个结点,修改指针域即可删除第n-k+1个结点;