一個筆試題的遞迴解法

來源:互聯網
上載者:User

// 找出倒數第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. }  

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.