面试题06. 从尾到头打印链表

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public int[] reversePrint(ListNode head) {
        //数组长度
        int length = 0;
        //创建虚拟头结点
        ListNode root = new ListNode(0);
        //next指向头结点
        root.next = head;
        //创建栈
        Stack<ListNode> stack = new Stack<>();
        //将链表中的元素压入栈中
        //同时让length++
        while(root.next != null){
            stack.push(root.next);
            root = root.next;
            length++;
        }
        //创建length长度的数组
        int []nums = new int[length];
        for(int i = 0;i < length;i++){
            //将出栈元素添加进数组
            nums[i] = stack.pop().val;
        }
        //返回数组
        return nums;
    }
}

猜你喜欢

转载自www.cnblogs.com/hzqshuai/p/12304763.html