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.