Advertisement
Guest User

Untitled

a guest
Apr 2nd, 2020
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.23 KB | None | 0 0
  1.     /**
  2.      * Insert value at specific position.
  3.      *
  4.      * Note: position 0 will update first MyLinkedListRecursive node
  5.      *
  6.      * @param value to add
  7.      * @param position to add value to.
  8.      */
  9.     public void insert(T value, int position) {
  10.  
  11.         // Base case
  12.         if (isEmpty()) {
  13.             add(value);  // When position > size. Add to end of list
  14.         }else if (position == 0) {
  15.             // Change the current MyLinkedListRecursive
  16.             LinkedListRecursive<T> current = new LinkedListRecursive<>();
  17.             current.head = head;
  18.             current.tail = tail;
  19.  
  20.             this.head = value;
  21.             this.tail = current;
  22.         }else {
  23.             // Recursion
  24.             tail.insert(value, position - 1);
  25.         }
  26.     }
  27.  
  28.     /* Alternative implementation
  29.     public void insert(T value, int position) {
  30.         if (isEmpty() || position == 0) {  //if position > size, add to end of list
  31.             MyLinkedListRecursive<T> add = new MyLinkedListRecursive<>();
  32.             add.tail = this.tail;
  33.             add.head = this.head;
  34.             this.head = value;
  35.             this.tail = add;
  36.         } else {
  37.             tail.insert(value,position - 1);
  38.         }
  39.     }
  40.      */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement