从尾到头打印链表

题目描述

输入一个链表,从尾到头打印链表每个节点的值。

有两种方法可以解决这个问题,第一种将链表翻转,遍历一遍,然后将所有的指针翻转;第二种利用递归思想

如果next不为空,则继续往下递归,当next为空时,输出。

 

第一种方法

 

public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
    	ArrayList<Integer> array=new ArrayList<Integer>();
        if(listNode==null){
        	return null;
        }else if(listNode.next==null){
        	array.add(listNode.val);
        	return array;
        }
        ListNode first=listNode;
        ListNode after=listNode.next;
        ListNode temp=null;
        first.next=null;
        while(after!=null){
        	temp=after.next;
        	after.next=first;
        	first=after;
        	after=temp;
        }
        
        temp=first;
        while(temp!=null){
        	array.add(temp.val);
        	temp=temp.next;
        } 
    	return array;
    }

 

 

第二种方法:

 public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
         ArrayList<Integer> array=new ArrayList<Integer>();
		 if(listNode==null)
			 return array;
		 else{
			 daozhuan(array,listNode);
		 }
		 
		 return array;
   }
   
   private void daozhuan(ArrayList<Integer> array,ListNode listNode){

		 if(listNode.next!=null)
			 daozhuan(array,listNode.next);
		 array.add(listNode.val);
   }
posted @ 2015-12-25 15:27  黄大仙爱编程  阅读(104)  评论(0)    收藏  举报