图书整理 I (图书整理 I)

 

思路:先查个数,后遍历链表

// @Title: 图书整理 I (图书整理 I)
// @Author: qisiii
// @Date: 2022-02-19 17:14:26
// @Runtime: 0 ms
// @Memory: 42 MB
// @comment: 先查个数,后遍历链表
// @flag: BLUE
/**
 * 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 i=0;ListNode temp;
        temp=head;
        while (temp!=null){
            temp=temp.next;
                        i++;
        }
        int[] result=new int[i];
        while(head!=null){
            result[--i]=head.val;
            head=head.next;
        }
        return result;
    }
}

+++ title = “图书整理 I (图书整理 I)” draft = false +++

思路:使用arraylist,空间o(N),时间o(2N)

// @Title: 图书整理 I (图书整理 I)
// @Author: qisiii
// @Date: 2022-02-19 17:05:55
// @Runtime: 4 ms
// @Memory: 41.9 MB
// @comment: 使用arraylist,空间o(N),时间o(2N)
// @flag: BLUE
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
       public int[] reversePrint(ListNode head) {
        List<Integer> result=new ArrayList<>();
        int i=0;
        while (head!=null){
           result.add(0,head.val);
            head=head.next;
        }
        int[] realResult=new int[result.size()];
        Iterator iterator = result.iterator();
        while (iterator.hasNext()){
            realResult[i++]= (int) iterator.next();
        }
        return realResult;
    }
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18