题解 | #删除链表的倒数第n个节点#
删除链表的倒数第n个节点
http://www.nowcoder.com/practice/f95dcdafbde44b22a6d741baf71653f6
/** * struct ListNode { * int val; * struct ListNode *next; * }; */ class Solution { public: /** * * @param head ListNode类 * @param n int整型 * @return ListNode类 */ ListNode* removeNthFromEnd(ListNode* head, int n) { // write code here if(head==nullptr || n<1) return nullptr; ListNode newHead(0); newHead.next=head; ListNode *l1=head; ListNode *l2=head; for(int i=0;i<n;i++){ l2=l2->next; } ListNode *p=&newHead; while(l2){ p=l1; l2=l2->next; l1=l1->next; } p->next=l1->next; delete l1; return newHead.next; } };