[Classic Interview Questions] Find the nth node at the bottom of a single-chain table

Source: Internet
Author: User

One of the frequently asked programming questions during the interview.

The most direct method is to traverse the single-chain table, write down the number of nodes in the linked list, and traverse the table again until the number of nodes minus N is reached, and the result is returned. In reality, if the number of linked lists is large and N is relatively small, This method requires about two traversal times. A simpler implementation method is to use dual pointers. One pointer starts to step N from the linked list header, and the other pointer starts from the beginning. The two pointers step together until they reach the end of the linked list. This is the node referred to by the second pointer, that is, the chain table, but the nth node. The implementation code is as follows:

Struct node * lastn (struct node * head, int N) {struct node * P, * q; If (n <1) {return NULL;} q = head; while (-- N) {If (! Q-> next) {return NULL;} q = Q-> next;} p = head; while (Q-> next) {P = p-> next; Q = Q-> next;} return P ;}

Check in special cases:

1. N is greater than the number of nodes

2. The parameter n is 0 or negative.

3. the header parameter is a null pointer.

The double-linked table method can solve many problems. Another example is to check whether a single-linked table has a ring. In this case, you can use two linked lists, one step at a time and two steps at a time. If there are two linked lists, they will meet each other.

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.