【LeetCode】從尾到頭反過來返回每個節點的值(用數組返回)day03

題目

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

示例 1:
輸入:head = [1,3,2]
輸出:[2,3,1]
限制:
0 <= 鏈表長度 <= 10000

第一次

//使用棧的特性先進後出
//複雜度O(n)
public int[] reversePrint(ListNode head) {
        Stack<ListNode> stack =  new Stack<ListNode>();
        ListNode temp = head;
        while(temp!= null){
           stack.push(temp);
           temp = temp.next;
           }
           int[]  result =  new int[stack.size()];
           for(int i = 0 ;  i< stack.size();i ++ ){
           result[i] = stack.pop().val;
           }
        return result;
          
    }
//自己腦瓜子有點問題
    public int[] reversePrint(ListNode head) {
        ListNode[] result = new ListNode[];
        ListNode temp = head;
        int count = 0;
        while(temp != null ){
            result[count] = temp;
            temp = temp.next;
            count++;
        }
        int[] resultV2 = new int[count];
        for(int i = 0; i<count; i++){
            resultV2[count] = result[i].val;
            count--;
            }
            return resultV2;
}

第三種解決方案

//純O(n)的複雜度
class Solution {
    public int[] reversePrint(ListNode head) {
        ListNode temp = head;
        int count = 0;
        while(temp != null ){
            temp = temp.next;
            count++;
        }
        int[] resultV2 = new int[count];
        temp = head;
        for(int i = count-1; i>=0; i--){
            resultV2[i] = temp.val;
            temp = temp.next;
        }
            return resultV2;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章