从尾到头打印链表
时间:2021-02-20 12:07:07
收藏:0
阅读:21
1、题目描述
-
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)
-
示例
-
输入:head = [1,3,2]
输出:[2,3,1]
-
2、解题思路
-
1、根据链表有效结点的个数确定数组长度length
-
2、使用临时变量遍历链表
-
3、确定当前结点在数组中存放的位置,放到数组中
-
因为是倒叙打印放到数组中,所以当前结点在数组中的位置应该是 length - index(index = 1,2,...,length)
-
-
也可以借助于栈的先入后出特性实现逆序效果
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)