剑指 Offer 06. 从尾到头打印链表
题目:从尾到头打印链表
-
LeetCode地址:剑指 Offer 06. 从尾到头打印链表
-
描述:输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
-
示例:
输入:head = [1,3,2] 输出:[2,3,1] 限制:0 <= 链表长度 <= 10000
题解:
-
思路:两次遍历单链表,第一次获取长度,根据长度创建数组,第二次遍历把数据存入结果数组。
-
代码:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public int[] reversePrint1(ListNode head) { //记录节点个数 int count = 0; ListNode tempNode = head; //获取链表长度 while (tempNode != null) { count++; tempNode = tempNode.next; } //根据链表长度,创建结果数组 int[] res = new int[count]; //临时指针重新指向头节点 tempNode = head; //再次遍历链表把节点的值倒序存入数组 while (tempNode != null) { res[--count] = tempNode.val; tempNode = tempNode.next; } return res; }
-
复杂度分析:
- 时间复杂度:O(n) 。
- 空间复杂度:O(1)。
-
测试: