面試題06. 從尾到頭打印鏈表【LeetCode劍指offer】

題目:

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

在這裏插入圖片描述

思路:

  1. 兩次遍歷鏈表,第一次得到鏈表的 length ;
  2. 定義一個返回數組,長度爲 鏈表的 length ;
  3. 爲數組反向賦值,賦值完成,也就將鏈表反向存儲到數組中。

實現:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
     public int[] reversePrint(ListNode head) {
        int count = 0;
        ListNode temp = head;
        while (temp != null) {
            count++;
            temp = temp.next;
        }

        int[] res = new int[count];
        for (int i = count - 1; i >= 0; i--) {
            res[i] = head.val;
            head = head.next;
        }
        return res;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章