剑指offer-面试题6-从头到尾打印链表

方法一:用栈基于循环实现

import java.util.ArrayList;
import java.util.Stack;
public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        Stack<Integer> arrayStack = new Stack<>();
        ArrayList<Integer> result = new ArrayList<>();
        ListNode current = listNode;
        while(current!=null){
            arrayStack.push(current.val);
            current = current.next;
        }
        while(!arrayStack.empty()){
            result.add(arrayStack.pop());
        }
        
        return result;
    }
}

方法二:递归

import java.util.ArrayList;
public class Solution {
    
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        
        ArrayList<Integer> result = new ArrayList<>();
        if(listNode==null){
            return result;
        }else{
            printListFromTailToHead(result,listNode);
            return result;
        }

    }
    
    private void printListFromTailToHead(ArrayList result,ListNode listNode) {
        
        if(listNode.next != null){
            printListFromTailToHead(result,listNode.next);
        }
        result.add(listNode.val);
    }
    
}

猜你喜欢

转载自blog.csdn.net/weixin_41993767/article/details/84372965