method One: Use two pointers p,q, first move the Q to the tail of the chain N-bit, and then the P, Q back together, then when Q reached the end of the linked list, p that point to the penultimate node of the list.
Copy Code code as follows:
node* find_nth_to_last (node* head,int N) {if (Head==null | | n<1) return NULL; node*p,*q; p=q=head. while (Q!=null && Amp n--) {q=q->next;} if (n>=0) return NULL; while (P!=null && q!=null) {p=p->next; q=q->next;} return p; }
method Two: The number of nodes can be calculated first, that is, to traverse the list from beginning to end, to get the number m, then the reciprocal nth element is also the first M-N+1 element. The same thinking as the method, but the specific mode of operation is different, code slightly.
Java code:
Copy Code code as follows:
LinkedListNode Nthtolast (linkedlistnode head, int n) {if (head = = NULL | | n &L T 1) {return null;} LinkedListNode P1 = head; LinkedListNode P2 = head; for (int j = 0; j < n-1; ++j) {//skip n-1 steps ahead if (P2 = null) {return null;//not found since list size & Lt n} p2 = P2.next; while (P2.next!= null) {p1 = P1.next; p2 = p2.next;} return p1; }