面试题6:从尾到头打印链表

2018-03-19  本文已影响11人  夹小欣

思路一:用栈

    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        
        Stack<Integer> stack = new Stack<Integer>();
        ArrayList<Integer> res = new ArrayList<Integer>();
// 不能是listNode.next!=null会空指针报错
        while(listNode!=null){
            stack.push(listNode.val);
            listNode = listNode.next;
        }
        while(!stack.isEmpty()){
            res.add(stack.pop());
        }
        return res;
    }

思路二:递归
如果链表太长,会导致递归层数过多,可能会溢出

public class Solution {
  ArrayList<Integer> res = new ArrayList<Integer>();
  public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
     if(listNode!=null)
     {printListFromTailToHead(listNode.next);
      res.add(listNode.val);}
      return res;
  }
上一篇 下一篇

猜你喜欢

热点阅读