跟我一起学算法系列5---从尾到头打印链表

 
 

1.题目描述输入一个链表,从尾到头打印链表每个节点的值。

2.算法分析这个题目有两种方式可以解。一种方式是采用递归,链表的首节点递归,直到最后一个节点先添加到list里。

第二种方式是利用Stack的特殊性,先进后出,先将所有节点从头到尾依次添加到栈,然后依次出栈。

3.代码实例(1)递归

ArrayList<Integer> mList = new ArrayList<Integer>();
public ArrayList<Integer> printListFromTailToHead(ListNode listNode){
        if(null != listNode)
    {
        if(null != listNode.next)
        {
        mList = printListFromTailToHead(listNode.next);
        }
            
            mList.add(new Integer(listNode.val));
    }
        
    return mList;
}

(2)利用Stack

public ArrayList<Integer> printListFromTailToHead(ListNode listNode){ 
        ArrayList<Integer> mList = new ArrayList<Integer>();
        ListNode head = listNode;
        Stack<Integer> stack = new Stack<Integer>();
    
        while(null != head)
        {
            stack.push(new Integer(head.val));
            head = head.next;
        }
        
        while(!stack.isEmpty())
        {
            mList.add(stack.pop());
        }
        
        return mList;
    }

猜你喜欢

转载自blog.csdn.net/wu__di/article/details/78575679