贸易网站开发/google关键词挖掘工具
剑指 Offer 06.从尾到头打印链表
题目描述
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例
输入:head = [1,3,2]
输出:[2,3,1]
限制
0 <= 链表长度 <= 10000
代码演示
Python3 递归法
class ListNode:def __init__(self, x):self.val = xself.next = Noneclass Solution:def reversePrint(self, head: ListNode) -> [int]:return self.reversePrint(head.next) + [head.val] if head else []if __name__ == "__main__":First = ListNode(1)Second = ListNode(3)Third = ListNode(2)First.next = SecondSecond.next = ThirdS = Solution()list = S.reversePrint(First)print(list)
Python3 递归法提交结果
执行用时:148 ms, 在所有 Python3 提交中击败了6.69% 的用户
内存消耗:24.2 MB, 在所有 Python3 提交中击败了9.49% 的用户
代码演示
Java 辅助栈
public class Interview06 {public static void main(String[] args) {Solution s = new Solution();ListNode head = new ListNode(1,new ListNode(3,new ListNode(2)));for (int i :s.reversePrint(head)) {System.out.print(i + " ");}}
}class ListNode {int val;ListNode next;ListNode(){}ListNode(int val) { this.val = val; }ListNode(int val, ListNode next) {this.val = val;this.next = next;}
}class Solution {public int[] reversePrint(ListNode head) {LinkedList<Integer> stack = new LinkedList<Integer>();while(head != null) {stack.addLast(head.val);head = head.next;}int n = stack.size();int[] array = new int[n];for(int i = 0; i < n; i++)array[i] = stack.removeLast();return array;}
}
Java 辅助栈提交结果
执行用时:1 ms, 在所有 Java 提交中击败了73.27% 的用户
内存消耗:38.9 MB, 在所有 Java 提交中击败了77.34% 的用户