首页 > 其他 > 详细

从尾到头打印链表

时间:2021-02-20 12:07:07      阅读:21      评论:0      收藏:0      [点我收藏+]

从尾到头打印链表

1、题目描述

  • 输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)

  • 示例

    • 输入:head = [1,3,2]
      输出:[2,3,1]

2、解题思路

  • 1、根据链表有效结点的个数确定数组长度length

  • 2、使用临时变量遍历链表

  • 3、确定当前结点在数组中存放的位置,放到数组中

    • 因为是倒叙打印放到数组中,所以当前结点在数组中的位置应该是 length - index(index = 1,2,...,length)

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)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!