剑指 Offer 06. 从尾到头打印链表

题目

剑指 Offer 06. 从尾到头打印链表

思路

利用栈后进先出的特性。
正向将链表节点全部压入栈中,再一个个弹出来,那么得到自然就是这个链表的从尾到头部的打印。

Code

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public int[] reversePrint(ListNode head) {
        Stack<Integer> stack=new Stack<>();
        ListNode p=head;
        while(p!=null){
            stack.push(p.val);
            p=p.next;
        }
        int []ans=new int [stack.size()];
        int idx=0;
        while(!stack.isEmpty()){
            ans[idx++]=stack.pop();
        }
        return ans;
    }
}

posted @ 2022-12-07 23:32  溯光6  阅读(5)  评论(0)    收藏  举报