/** * struct ListNode { * int val; * struct ListNode *next; * }; */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @param n int整型 * @return ListNode类 */ struct ListNode* removeNthFromEnd(struct ListNode* head, int n ) { //思路 //遍历链表计算总长度size,设置一个结点指针和前序结点指针,从头遍历size-k个结点,找到目标结点进行删除 struct ListNode* pTmp = head; struct ListNode headNode = { .next = head }; struct ListNode* pTmpPre = &headNode; int size = 0; if ((head == NULL) || (n <= 0)) { return NULL; } //遍历链表计算总长度size while (pTmp != NULL) { pTmp = pTmp->next; size++; } if (size < n) { return NULL; } pTmp = head; //从头遍历size - k个结点 for (size_t i = 0; i < size - n; i++) { pTmp = pTmp->next; pTmpPre = pTmpPre->next; } pTmpPre->next = pTmp->next; //删除目标结点 return headNode.next; }