题目要求
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
输入:head = [1,3,2]
输出:[2,3,1]
原题链接:剑指 Offer 06. 从尾到头打印链表
解题过程
解题过程和反转链表基本一致,可参考反转图解:LeetCode-反转单链表(头插法、双指针、辅助栈)
自己再写点方法,将链表数据存入数组输出即可。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| class Solution { public int[] reversePrint(ListNode head) { int[] arr = new int[size(head)]; if(head == null) return arr; if(head.next == null){ return listToArray(arr,head); }
Stack<ListNode> stack = new Stack<>(); while(head != null){ stack.push(head); head = head.next; }
ListNode newHead = stack.pop(); ListNode tmp = newHead;
while(!stack.isEmpty()){ ListNode cur = stack.pop(); tmp.next = cur; tmp = cur; }
tmp.next = null; return listToArray(arr,newHead);
}
public int[] listToArray(int[] arr, ListNode head){ for(int i = 0; i < arr.length; i++){ arr[i] = head.val; head = head.next; } return arr; }
public int size(ListNode head){ int count = 0; ListNode cur = head; while(cur != null){ count++; cur = cur.next; } return count; }
}
|