jake1036

面试100 31倒序输出链表中的字符

     面试100 31倒序输出链表中的字符

  一 问题描述
         考虑使用递归,将每次遍历的节点,存储在一个栈结构中。 遍历完毕之后,依次处理栈中的数据 。

  二 延伸扩展
        相似题目有,不在函数内申明变量,求字符串的长度。

 代码如下:
    
#include <iostream>
#include 
<vector>
#include 
<iterator>

  
using namespace std ;
  
  
  
struct ListNode
  
{
    ListNode 
* next ;
    
int data ;             
  }
 ;
  
  ListNode head ; 
//头节点 
  const int N = 10 ;
 
  
void buildList( vector <int> &v) //遍历stl数组,依次取得数据 
  {
     vector
<int>::iterator iter = v.begin() ;  
     
for(;iter < v.end() ; iter++)
     
{
        ListNode  
* temp = (ListNode  *)malloc(sizeof(ListNode)) ; 
        temp
->data = *iter ;
        temp
->next = head.next ;  
        head.next 
= temp ;
     }
    
  }

  
 
  
void visit(ListNode *  p)
  
{
     
if(p)
     
{
       visit(p
->next) ;
       cout
<<p->data ;      
     }
            
  }

  
  
  
int  length(char * s)
  
{
       
if(!s)
          
return 0 ;
       
if(*s)   
         
return 1 + length(s + 1) ;
       
else
         
return 0 ;  
  }

  
  
  
int main()
  
{
    head.next 
= 0 ;
    head.data 
= 1;   
      
    vector 
<int> v ;
    
for(int i = 0 ; i < N ;i++)  
      v.push_back(i) ;
      
    buildList(v) ;
    visit(head.next) ;  
    
    
char s[10= "fdfdf" ;
    cout
<<length(s)<<endl;
    
    system(
"pause") ;   
    
return 0 ;    
  }

posted on 2011-05-21 15:03 kahn 阅读(489) 评论(0)  编辑 收藏 引用 所属分类: 算法相关


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理