Advertisement
FNSY

1265. Print Immutable Linked List in Reverse Solution

May 7th, 2022
1,166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.73 KB | None | 0 0
  1. //O(n) Space, O(n) Time
  2. class Solution {
  3.     public void printLinkedListInReverse(ImmutableListNode head) {
  4.         List<ImmutableListNode> temp = new ArrayList<>();
  5.         while (head != null) {
  6.             temp.add(head);
  7.             head = head.getNext();
  8.         }
  9.         for (int i = temp.size() - 1; i >= 0; i--) temp.get(i).printValue();
  10.     }
  11. }
  12.  
  13.  
  14. //O(1) Space, O(n ^ 2) Time
  15. class Solution {
  16.     public void printLinkedListInReverse(ImmutableListNode head) {
  17.         ImmutableListNode next = null;
  18.         while (next != head) {
  19.             ImmutableListNode cur = head;
  20.             while (cur.getNext() != next) cur = cur.getNext();
  21.             cur.printValue();
  22.             next = cur;
  23.         }
  24.     }
  25. }
  26.  
  27.  
  28. //O(sqrt(n)) Space, O(n) Time
  29. class Solution {
  30.     public void printLinkedListInReverse(ImmutableListNode head) {
  31.         int n = 0;
  32.         ImmutableListNode p = head;
  33.         while (p != null) {
  34.             n++;
  35.             p = p.getNext();
  36.         }
  37.        
  38.         int len = (int)Math.sqrt(n);
  39.         List<ImmutableListNode> start = new ArrayList<>();
  40.         for (int i = 0; i < n; i++) {
  41.             if (i % len == 0) start.add(head);
  42.             head = head.getNext();
  43.         }
  44.        
  45.         start.add(null);
  46.         for (int i = start.size() - 2; i >= 0; i--) {
  47.             print(start.get(i), start.get(i + 1));
  48.         }
  49.     }
  50.    
  51.     private void print(ImmutableListNode head, ImmutableListNode end) {
  52.         List<ImmutableListNode> temp = new ArrayList<>();
  53.         while (head != end) {
  54.             temp.add(head);
  55.             head = head.getNext();
  56.         }
  57.         for (int i = temp.size() - 1; i >= 0; i--) {
  58.             temp.get(i).printValue();
  59.         }
  60.     }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement