从尾到头打印链表

时间:2021-02-20 12:07:07   收藏:0   阅读:21

从尾到头打印链表

1、题目描述

2、解题思路

3、代码

public static int[] reversePrint(ListNode head) {
?
    int listLength = getListLength(head);
    if (listLength == 0){
        return new int[]{0};
    }
?
    // 定义数组
    int[] result = new int[listLength];
?
    ListNode temp = head;
    int index = 1;
    while(temp != null){
        int countDownIndex = listLength - index;
        result[countDownIndex] = temp.val;
        index ++;
        temp = temp.next;
    }
?
    return result;
}
?
public static int getListLength(ListNode head){
?
    if (head == null){
        return 0;
    }
?
    // 使用length统计结点个数
    int length = 0;
    // 使用临时变量temp做可移动变量,遍历链表
    ListNode temp = head;
    while(temp != null){
        length ++;
        temp = temp.next;
    }
?
    return length;
}

 

 



原文:https://www.cnblogs.com/LittleSkinny/p/14419550.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!