一个笔试题的递归解法

// 找出倒数第n个节点,返回其指针  
// 约定: 倒数第一个节点:为最后一个节点

Code:
  1. #include <iostream>  
  2. using namespace std;  
  3. typedef struct node  
  4. {    
  5.      int data;    
  6.     struct node *next;    
  7. } link_node;  
  8.   
  9. link_node * root = NULL;  
  10.   
  11. void Initialize(int a[],int len)  
  12. {  
  13.     for (int i = 0;i<len;i++)  
  14.     {  
  15.         link_node * node = new link_node;  
  16.         node->data = a[i];  
  17.         node->next = root;  
  18.         root = node;  
  19.     }  
  20. }  
  21. void Print(link_node * _root)  
  22. {  
  23.     while (_root!=NULL)  
  24.     {  
  25.         cout << _root->data << " ";  
  26.         _root = _root->next;  
  27.     }  
  28.     cout << endl;  
  29. }  
  30. // 找出倒数第n个节点,返回其指针     
  31. // 约定: 倒数第一个节点:为最后一个节点  
  32. link_node* findLastN(link_node * _root,int len,int n)  
  33. {  
  34.     if (_root == NULL || n > len)  
  35.     {  
  36.         return NULL;  
  37.     }  
  38.     if (len == n)  
  39.     {  
  40.         return _root;  
  41.     }  
  42.     return findLastN(_root->next,len - 1,n);  
  43. }  
  44. int CalculateLen(link_node* node)  
  45. {  
  46.     int len = 0;  
  47.       
  48.     while (node!=NULL)  
  49.     {  
  50.         len ++;  
  51.         node = node->next;  
  52.     }  
  53.     return len;  
  54. }  
  55.   
  56. void main()  
  57. {  
  58.     int a[10] = {10,9,8,7,6,5,4,3,2,1};  
  59.     Initialize(a,10);  
  60.     Print(root);  
  61.     int len = CalculateLen(root);  
  62.   
  63.     int n;  
  64.     while (1)  
  65.     {  
  66.         cin >> n;  
  67.         if (n == -1)  
  68.         {  
  69.             break;  
  70.         }  
  71.         link_node * node = findLastN(root,len,n);  
  72.         if (node == NULL)  
  73.         {  
  74.             cout << "no found" << endl;  
  75.         }else{  
  76.             cout << node->data<<endl;  
  77.         }  
  78.   
  79.     }  
  80. }  

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值