|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import java.util.Stack; |
| 4 | + |
| 5 | +/** |
| 6 | + * 1265. Print Immutable Linked List in Reverse |
| 7 | + * |
| 8 | + * You are given an immutable linked list, print out all values of each node in reverse with the help of the following interface: |
| 9 | + * ImmutableListNode: An interface of immutable linked list, you are given the head of the list. |
| 10 | + * You need to use the following functions to access the linked list (you can't access the ImmutableListNode directly): |
| 11 | + * ImmutableListNode.printValue(): Print value of the current node. |
| 12 | + * ImmutableListNode.getNext(): Return the next node. |
| 13 | + * The input is only given to initialize the linked list internally. |
| 14 | + * You must solve this problem without modifying the linked list. In other words, you must operate the linked list using only the mentioned APIs. |
| 15 | + * |
| 16 | + * Follow up: |
| 17 | + * Could you solve this problem in: |
| 18 | + * Constant space complexity? |
| 19 | + * Linear time complexity and less than linear space complexity? |
| 20 | + * |
| 21 | + * Example 1: |
| 22 | + * Input: head = [1,2,3,4] |
| 23 | + * Output: [4,3,2,1] |
| 24 | + * |
| 25 | + * Example 2: |
| 26 | + * Input: head = [0,-4,-1,3,-5] |
| 27 | + * Output: [-5,3,-1,-4,0] |
| 28 | + * |
| 29 | + * Example 3: |
| 30 | + * Input: head = [-2,0,6,4,4,-6] |
| 31 | + * Output: [-6,4,4,6,0,-2] |
| 32 | + * |
| 33 | + * Constraints: |
| 34 | + * The length of the linked list is between [1, 1000]. |
| 35 | + * The value of each node in the linked list is between [-1000, 1000]. |
| 36 | + * */ |
| 37 | +public class _1265 { |
| 38 | + |
| 39 | + interface ImmutableListNode { |
| 40 | + ImmutableListNode getNext(); |
| 41 | + |
| 42 | + void printValue(); |
| 43 | + } |
| 44 | + |
| 45 | + public static class Solution1 { |
| 46 | + public void printLinkedListInReverse(ImmutableListNode head) { |
| 47 | + Stack<ImmutableListNode> stack = new Stack(); |
| 48 | + while (head != null) { |
| 49 | + stack.add(head); |
| 50 | + head = head.getNext(); |
| 51 | + } |
| 52 | + while (!stack.isEmpty()) { |
| 53 | + head = stack.pop(); |
| 54 | + head.printValue(); |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | +} |
0 commit comments