This problem can be solved using the double pointer method. The distance between the two pointers p and q is kept at N-1, and then the Q is moved to the last element of the list, then P points to the nth node from the end. To delete this node, there are two cases: one is that the node is the head, and the other is the intermediate node. In the first case, you can simply use the following operations: Head = head-> next. In the second case, we need to introduce an additional pointer prev_p pointing to the previous node of P, so that the node can be deleted through prev_p-> next = prev_p-> next. The Code is as follows:
1 class solution {2 public: 3 listnode * removenthfromend (listnode * head, int N) {4 listnode * P = head, * q = head, * prev_p = NULL; 5 For (INT I = 0; I <n-1; I ++) 6 q = Q-> next; 7 for (; q-> next; q = Q-> next, prev_p = P, P = p-> next); 8 If (P = head) Head = head-> next; 9 else 10 prev_p-> next = p-> next; 11 return head; 12} 13 };