Two methods to find the reciprocal nth node elements in the list _java

Source: Internet
Author: User
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; }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.