面試題06. 從尾到頭打印鏈表

輸入一個鏈表的頭節點,從尾到頭反過來返回每個節點的值(用數組返回)。

/**
 * 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;
    }
    */

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章