题解 | #删除链表的倒数第n个节点#
删除链表的倒数第n个节点
https://www.nowcoder.com/practice/f95dcdafbde44b22a6d741baf71653f6
/** * struct ListNode { * int val; * struct ListNode *next; * }; */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @param n int整型 * @return ListNode类 */ struct ListNode* removeNthFromEnd(struct ListNode* head, int n ) { //通过算法找到倒数第n+1个节点,但实际上是删除倒数第n个 if (head==NULL) return NULL; int num=0; struct ListNode*cur=head; while(cur) { num++; cur=cur->next; } cur=head; //注意这里要判断一下删除第一个元素的情况,因为会改变返回的地址 if(num==n) { struct ListNode*newhead=head->next; free(head); head=NULL; return newhead; } while(num-n-1) { if(cur) cur=cur->next; n++; } //记录下一个节点的信息 struct ListNode*next=cur->next; struct ListNode*nextnext=next->next; free(next); next=NULL; cur->next=nextnext; return head; }