// 找出倒数第n个节点,返回其指针
// 约定: 倒数第一个节点:为最后一个节点
- #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;
- }
- // 找出倒数第n个节点,返回其指针
- // 约定: 倒数第一个节点:为最后一个节点
- 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;
- }
- }
- }