// Find the nth last node and return its pointer
// Convention: Last node: Last Node
Code:
- # Include <iostream>
- Using namespace STD;
- Typedef struct Node
- {
- Int data;
- Struct node * next;
- } Link_node;
- Link_node * root = NULL;
- Void initialize (int A [], int Len)
- {
- For (INT I = 0; I <Len; I ++)
- {
- Link_node * node = new link_node;
- Node-> DATA = A [I];
- Node-> next = root;
- Root = node;
- }
- }
- Void print (link_node * _ root)
- {
- While (_ root! = NULL)
- {
- Cout <_ root-> data <"";
- _ Root = _ root-> next;
- }
- Cout <Endl;
- }
- // Find the nth last node and return its pointer
- // Convention: Last node: Last Node
- Link_node * findlastn (link_node * _ root, int Len, int N)
- {
- If (_ root = NULL | n> Len)
- {
- Return NULL;
- }
- If (LEN = N)
- {
- Return _ root;
- }
- Return findlastn (_ root-> next, len-1, n );
- }
- Int calculatelen (link_node * node)
- {
- Int Len = 0;
- While (node! = NULL)
- {
- Len ++;
- Node = node-> next;
- }
- Return Len;
- }
- Void main ()
- {
- Int A [10] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
- Initialize (A, 10 );
- Print (Root );
- Int Len = calculatelen (Root );
- Int N;
- While (1)
- {
- Cin> N;
- If (n =-1)
- {
- Break;
- }
- Link_node * node = findlastn (root, Len, N );
- If (node = NULL)
- {
- Cout <"No found" <Endl;
- } Else {
- Cout <node-> data <Endl;
- }
- }
- }