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

让人想犯罪 __ 提交于 2020-03-01 18:12:49

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

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
 import java.util.*;
class Solution {
    
    public int[] reversePrint(ListNode head) {
        /*
        Stack<Integer> stack = new Stack<>();
        while(head != null){
            stack.push(head.val);
            head = head.next;
        }
        int[] arr = new int[stack.size()];
        for(int i = 0; i < arr.length; i++){
            arr[i] = stack.pop();
        }
        return arr;
        */
        int len = 0;
        ListNode cur = head;
        while(cur != null){
            len++;
            cur = cur.next;
        }
        int[] arr = new int[len];
        for(int i = len - 1; i >= 0; i--){
            arr[i] = head.val;
            head = head.next;
        }
        return arr;

    }
    
    /* 反转链表
    public ListNode revListNode(ListNode head) {
        ListNode cur = head;
        ListNode prev = null;
        while(cur != null){
            ListNode next = cur.next;
            cur.next = prev;
            prev = cur;
            cur = next;
        }
        return cur;
    }
    */

}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!