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

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

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

示例 1:

輸入:head = [1,3,2]
輸出:[2,3,1]

限制:
0 <= 鏈表長度 <= 10000

【解題思路1】棧

/**
 * 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<ListNode> stack = new Stack<ListNode>();
        ListNode temp = head;
        while (temp != null) {
            stack.push(temp);
            temp = temp.next;
        }
        int size = stack.size();
        int[] ans = new int[size];
        for (int i = 0; i < size; i++) {
            ans[i] = stack.pop().val;
        }
        return ans;
    }
}

【解題思路2】先獲取元素個數

遍歷兩遍,獲取元素個數,直接倒着存進數組

class Solution {
    public int[] reversePrint(ListNode head) {
        ListNode currNode = head;
        int len = 0;
        while(currNode != null){
            len ++;
            currNode = currNode.next;
        }
        int[] ans = new int[len];
        
        currNode = head;
        while(currNode != null){
            ans[len - 1] = currNode.val;
            len --;
            currNode = currNode.next;
        }
        return ans;
    }
}

【解題思路3】反轉鏈表

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