day04

从头到尾打印链表

问题:输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

1.利用栈

public class test01 {
    public int[] reversePrint(ListNode head) {
        //核心思想是利用栈
        //创建栈
        Stack<ListNode> stack = new Stack<ListNode>();
        //创建一个指针,初始时指向头结点
        ListNode temp = head;
        //当指针指向的元素不为空时,进行压栈
        while (temp!=null){
            stack.push(temp);
            temp=temp.next;
        }
        //获取栈的大小
        int size = stack.size();
        //创建一个数组,大小为size
        int[] print = new int[size];
        //从栈内弹出一个结点
        for (int i = 0;i<size;i++){
            print[i] = stack.pop().val;
        }
        return print;

    }
}

2.递归法

/*
算法流程:
1.递归阶段:每次传入head.next,以head=null为递归终止条件,此时直接返回
2.回溯阶段:层层回溯时,将当前节点值加入列表
3.最终,将列表tmp转换成数组res,并且返回即可
 */
package day04;

import java.util.ArrayList;

public class test02 {
    ArrayList<Integer> tmp = new ArrayList<Integer>();
    public int[] reversePrint(ListNode head){
        recur(head);
        int[] res = new int[tmp.size()];
        for (int i=0;i<res.length;i++){
            res[i] = tmp.get(i);
         return res;
        }
        void recur(ListNode head){
            if (head==null) return;
            recur(head.next);
            tmp.add(head.val);
        }
    }
}

 

posted @ 2020-04-12 21:37  行之!  阅读(131)  评论(0编辑  收藏  举报