Filip_Markoski

[ADSx] - LinkedListFun

Jan 29th, 2018
221
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 27.11 KB | None | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.InputStreamReader;
  3. import java.util.Iterator;
  4. import java.util.NoSuchElementException;
  5. import java.util.Stack;
  6.  
  7. class SLLNode<E> {
  8.     protected E element;
  9.     protected SLLNode<E> succ;
  10.  
  11.     public SLLNode(E elem, SLLNode<E> succ) {
  12.         this.element = elem;
  13.         this.succ = succ;
  14.     }
  15.  
  16.     @Override
  17.     public String toString() {
  18.         //    return "(" + element.toString() + ")";
  19.         return element.toString();
  20.     }
  21. }
  22.  
  23. class SLL<E> {
  24.     private SLLNode<E> first;
  25.  
  26.     public SLL() {
  27.         // Construct an empty SLL
  28.         this.first = null;
  29.     }
  30.  
  31.     public void deleteList() {
  32.         first = null;
  33.     }
  34.  
  35.     public int length() {
  36.         int ret;
  37.         if (first != null) {
  38.             SLLNode<E> tmp = first;
  39.             ret = 1;
  40.             while (tmp.succ != null) {
  41.                 tmp = tmp.succ;
  42.                 ret++;
  43.             }
  44.             return ret;
  45.         } else
  46.             return 0;
  47.  
  48.     }
  49.  
  50.     @Override
  51.     public String toString() {
  52.         StringBuilder sb = new StringBuilder();
  53.         if (first != null) {
  54.             SLLNode<E> tmp = first;
  55.             sb.append(tmp).append(" ");
  56.             while (tmp.succ != null) {
  57.                 tmp = tmp.succ;
  58.                 sb.append(tmp).append(" ");
  59.             }
  60.         } else
  61.             sb = new StringBuilder("Prazna lista!!!");
  62.         return sb.toString();
  63.     }
  64.  
  65.     public void insertFirst(E o) {
  66.         SLLNode<E> ins = new SLLNode<E>(o, first);
  67.         first = ins;
  68.     }
  69.  
  70.     public void insertAfter(E o, SLLNode<E> node) {
  71.         if (node != null) {
  72.             SLLNode<E> ins = new SLLNode<E>(o, node.succ);
  73.             node.succ = ins;
  74.         } else {
  75.             System.out.println("Dadenot jazol e null");
  76.         }
  77.     }
  78.  
  79.     public void insertBefore(E o, SLLNode<E> before) {
  80.  
  81.         if (first != null) {
  82.             SLLNode<E> tmp = first;
  83.             if (first == before) {
  84.                 this.insertFirst(o);
  85.                 return;
  86.             }
  87.             //ako first!=before
  88.             while (tmp.succ != before)
  89.                 tmp = tmp.succ;
  90.             if (tmp.succ == before) {
  91.                 SLLNode<E> ins = new SLLNode<E>(o, before);
  92.                 tmp.succ = ins;
  93.             } else {
  94.                 System.out.println("Elementot ne postoi vo listata");
  95.             }
  96.         } else {
  97.             System.out.println("Listata e prazna");
  98.         }
  99.     }
  100.  
  101.     public void insertLast(E o) {
  102.         if (first != null) {
  103.             SLLNode<E> tmp = first;
  104.             while (tmp.succ != null)
  105.                 tmp = tmp.succ;
  106.             SLLNode<E> ins = new SLLNode<E>(o, null);
  107.             tmp.succ = ins;
  108.         } else {
  109.             insertFirst(o);
  110.         }
  111.     }
  112.  
  113.     public E deleteFirst() {
  114.         if (first != null) {
  115.             SLLNode<E> tmp = first;
  116.             first = first.succ;
  117.             return tmp.element;
  118.         } else {
  119.             System.out.println("Listata e prazna");
  120.             return null;
  121.         }
  122.     }
  123.  
  124.     public E delete(SLLNode<E> node) {
  125.         if (first != null) {
  126.             SLLNode<E> tmp = first;
  127.             if (first == node) {
  128.                 return this.deleteFirst();
  129.             }
  130.             while (tmp.succ != node && tmp.succ.succ != null)
  131.                 tmp = tmp.succ;
  132.             if (tmp.succ == node) {
  133.                 tmp.succ = tmp.succ.succ;
  134.                 return node.element;
  135.             } else {
  136.                 System.out.println("Elementot ne postoi vo listata");
  137.                 return null;
  138.             }
  139.         } else {
  140.             System.out.println("Listata e prazna");
  141.             return null;
  142.         }
  143.  
  144.     }
  145.  
  146.     public SLLNode<E> getFirst() {
  147.         return first;
  148.     }
  149.  
  150.     public void setFirst(SLLNode<E> first) {
  151.         this.first = first;
  152.     }
  153.  
  154.     public SLLNode<E> find(E o) {
  155.         if (first != null) {
  156.             SLLNode<E> tmp = first;
  157.             while (tmp.element != o && tmp.succ != null)
  158.                 tmp = tmp.succ;
  159.             if (tmp.element == o) {
  160.                 return tmp;
  161.             } else {
  162.                 System.out.println("Elementot ne postoi vo listata");
  163.             }
  164.         } else {
  165.             System.out.println("Listata e prazna");
  166.         }
  167.         return first;
  168.     }
  169.  
  170.     public Iterator<E> iterator() {
  171.         // Return an iterator that visits all elements of this list, in left-to-right order.
  172.         return new LRIterator<E>();
  173.     }
  174.  
  175.     // //////////Inner class ////////////
  176.  
  177.     private class LRIterator<E> implements Iterator<E> {
  178.  
  179.         private SLLNode<E> place, curr;
  180.  
  181.         private LRIterator() {
  182.             place = (SLLNode<E>) first;
  183.             curr = null;
  184.         }
  185.  
  186.         public boolean hasNext() {
  187.             return (place != null);
  188.         }
  189.  
  190.         public E next() {
  191.             if (place == null)
  192.                 throw new NoSuchElementException();
  193.             E nextElem = place.element;
  194.             curr = place;
  195.             place = place.succ;
  196.             return nextElem;
  197.         }
  198.  
  199.         public void remove() {
  200.             //Not implemented
  201.         }
  202.     }
  203.  
  204.     public <E extends Number> SLLNode<E> insertFirst(E element, SLLNode<E> first) {
  205.         SLLNode<E> insert = new SLLNode<E>(element, first);
  206.         return insert;
  207.     }
  208.  
  209.     public <E extends Number> void insertBefore(E element, SLLNode<E> first, SLLNode<E> before) {
  210.         if (first != null) {
  211.             SLLNode<E> tmp = first;
  212.             if (first == before) {
  213.                 insertFirst(element, first);
  214.                 return;
  215.             }
  216.             //ako first!=before
  217.             while (tmp.succ != before)
  218.                 tmp = tmp.succ;
  219.  
  220.             if (tmp.succ == before) {
  221.                 SLLNode<E> ins = new SLLNode<E>(element, before);
  222.                 tmp.succ = ins;
  223.             } else {
  224.                 System.out.println("Elementot ne postoi vo listata");
  225.             }
  226.         } else {
  227.             System.out.println("Listata e prazna");
  228.         }
  229.     }
  230.  
  231.     public void mirror() {
  232.         if (first != null) {
  233.             SLLNode<E> tmp = first;
  234.             SLLNode<E> newsucc = null;
  235.             SLLNode<E> next;
  236.  
  237.             while (tmp != null) {
  238.                 next = tmp.succ;
  239.                 tmp.succ = newsucc;
  240.                 newsucc = tmp;
  241.                 tmp = next;
  242.             }
  243.             first = newsucc;
  244.         }
  245.  
  246.     }
  247.  
  248.     public void merge(SLL<E> in) {
  249.         if (first != null) {
  250.             SLLNode<E> tmp = first;
  251.             while (tmp.succ != null)
  252.                 tmp = tmp.succ;
  253.             tmp.succ = in.getFirst();
  254.         } else {
  255.             first = in.getFirst();
  256.         }
  257.     }
  258.  
  259.     public void deleteDuplicates() {
  260.         /**
  261.          * https://www.geeksforgeeks.org/remove-duplicates-from-an-unsorted-linked-list/
  262.          */
  263.  
  264.         if (first != null) {
  265.             SLLNode<E> i = null, j = null;
  266.             i = first;
  267.  
  268.             /* Pick elements one by one */
  269.             while (i != null && i.succ != null) {
  270.                 j = i;
  271.  
  272.                 /* Compare the picked element with rest of the elements */
  273.                 while (j.succ != null) {
  274.  
  275.                     /* If duplicate then delete it */
  276.                     if (i.element == j.succ.element) {
  277.  
  278.                         /* sequence of steps is important here */
  279.                         j.succ = j.succ.succ;
  280.  
  281.                         System.gc();
  282.                     } else /* This is tricky */ {
  283.                         j = j.succ;
  284.                     }
  285.                 }
  286.                 i = i.succ;
  287.             }
  288.         } else System.out.println("The linked list is empty.");
  289.     }
  290.  
  291.     public void print_recursive_reverse(SLLNode<E> node) {
  292.         if (node == null) return;
  293.         print_recursive_reverse(node.succ);
  294.         if (node.succ == null) System.out.print(node.element);
  295.         else System.out.print("->" + node.element);
  296.     }
  297.  
  298.     public SLLNode<E> reverse(SLL<E> list) {
  299.         SLLNode<E> temp = list.getFirst();
  300.  
  301.         int length = list.length();
  302.         for (int i = 0; i < length; i++) {
  303.             list.insertFirst(temp.succ.element);
  304.             list.getFirst().succ = temp.succ.succ;
  305.             list.insertLast(temp.element);
  306.             temp = temp.succ;
  307.         }
  308.         temp = list.getFirst();
  309.         return temp;
  310.     }
  311.  
  312.     public void pairwiseSwapData() {
  313.         SLLNode<E> temp = this.getFirst();
  314.         E temp2;
  315.         while (temp != null && temp.succ != null) {
  316.             temp2 = temp.succ.element;
  317.             temp.succ.element = temp.element;
  318.             temp.element = temp2;
  319.  
  320.             temp = temp.succ.succ;
  321.         }
  322.     }
  323.  
  324.     public SLLNode<E> reverse(SLLNode<E> node) {
  325.         /**
  326.          * https://www.geeksforgeeks.org/reverse-a-linked-list/
  327.          * */
  328.         SLLNode<E> current = node;
  329.         SLLNode<E> following = null;
  330.         SLLNode<E> previous = null;
  331.  
  332.         while (current != null) {
  333.             following = current.succ;
  334.             current.succ = previous;
  335.             previous = current;
  336.             current = following;
  337.         }
  338.  
  339.         node = previous;
  340.         return node;
  341.     }
  342.  
  343.     public SLLNode<E> reverseGroupKRecursion(SLLNode<E> node, int size) {
  344.         /**
  345.          * https://www.geeksforgeeks.org/reverse-a-list-in-groups-of-given-size/
  346.          * */
  347.         SLLNode<E> current = node;
  348.         SLLNode<E> following = null;
  349.         SLLNode<E> previous = null;
  350.  
  351.         int count = 0;
  352.  
  353.         while (count < size && current != null) {
  354.             following = current.succ;
  355.             current.succ = previous;
  356.             previous = current;
  357.             current = following;
  358.             count++;
  359.         }
  360.  
  361.         if (following != null) node.succ = reverseGroupKRecursion(following, size);
  362.  
  363.         return previous;
  364.     }
  365.  
  366.     public SLLNode<E> reverseGroupKStack(SLLNode<E> node, int size) {
  367.         /**
  368.          * https://www.geeksforgeeks.org/reverse-linked-list-groups-given-size-set-2/
  369.          * */
  370.         Stack<SLLNode<E>> stack = new Stack<>();
  371.  
  372.         SLLNode<E> current = node;
  373.         SLLNode<E> following = null;
  374.         SLLNode<E> previous = null;
  375.  
  376.         while (current != null) {
  377.  
  378.             int count = 0;
  379.  
  380.             while (current != null && count < size) {
  381.                 stack.push(current);
  382.                 current = current.succ;
  383.                 count++;
  384.             }
  385.  
  386.             while (!stack.isEmpty()) {
  387.                 if (previous == null) {
  388.                     previous = stack.pop();
  389.                     node = previous;
  390.                 } else {
  391.                     previous.succ = stack.pop();
  392.                     previous = previous.succ;
  393.                 }
  394.             }
  395.         }
  396.  
  397.         previous.succ = null;
  398.  
  399.         return node;
  400.     }
  401.  
  402.     public SLLNode<E> reverseBetween(SLLNode<E> node, int start, int end) {
  403.         if (start == end) return node;
  404.  
  405.         SLLNode<E> nodeStart = null;
  406.         SLLNode<E> nodeEnd = null;
  407.         SLLNode<E> nodeStart_Previous = null;
  408.         SLLNode<E> nodeEnd_Following = null;
  409.  
  410.         int count = 1;
  411.         SLLNode<E> current = node;
  412.  
  413.         while (count <= end && current != null) {
  414.             if (count < start) {
  415.                 nodeStart_Previous = current;
  416.             }
  417.  
  418.             if (count == start) {
  419.                 nodeStart = current;
  420.             }
  421.  
  422.             if (count == end) {
  423.                 nodeEnd = current;
  424.                 nodeEnd_Following = current.succ;
  425.             }
  426.  
  427.             current = current.succ;
  428.             count++;
  429.         }
  430.         nodeEnd.succ = null;
  431.  
  432.         nodeEnd = reverse(nodeStart);
  433.  
  434.         if (nodeStart_Previous != null) {
  435.             nodeStart_Previous.succ = nodeEnd;
  436.         } else {
  437.             node = nodeEnd;
  438.         }
  439.  
  440.         nodeStart.succ = nodeEnd_Following;
  441.         return node;
  442.     }
  443.  
  444.     public <E extends Number> SLLNode<E> insertArithmeticalMeans(SLLNode<E> node) {
  445.  
  446.         SLLNode<E> previous = node;
  447.         SLLNode<E> current = node.succ;
  448.         SLLNode<E> following = node.succ.succ;
  449.  
  450.         while (current != null) {
  451.  
  452.             Integer a = previous.element.intValue();
  453.             Integer b = current.element.intValue();
  454.  
  455.             Integer mean = (a + b) / 2;
  456.  
  457.             insertBefore((E) mean, node, current);
  458.  
  459.             System.out.print(previous + " " + current + "\n");
  460.  
  461.             previous = current;
  462.             current = current.succ;
  463.         }
  464.         return node;
  465.     }
  466.  
  467. }
  468.  
  469. class DetectAndRemoveLoop {
  470.     static Node head;
  471.  
  472.     /**
  473.      * https://www.geeksforgeeks.org/detect-and-remove-loop-in-a-linked-list/
  474.      * */
  475.  
  476.     static class Node {
  477.         int data;
  478.         Node next;
  479.  
  480.         Node(int d) {
  481.             data = d;
  482.             next = null;
  483.         }
  484.     }
  485.  
  486.     // Function that detects loop in the list
  487.     int detectAndRemoveLoop(Node node) {
  488.         Node slow = node, fast = node;
  489.         while (slow != null && fast != null && fast.next != null) {
  490.             slow = slow.next;
  491.             fast = fast.next.next;
  492.  
  493.             // If slow and fast meet at same point then loop is present
  494.             if (slow == fast) {
  495.                 removeLoop(slow, node);
  496.                 return 1;
  497.             }
  498.         }
  499.         return 0;
  500.     }
  501.  
  502.     // Function to remove loop
  503.     void removeLoop(Node loop, Node curr) {
  504.         Node ptr1 = null, ptr2 = null;
  505.  
  506.         /* Set a pointer to the beging of the Linked List and
  507.          move it one by one to find the first node which is
  508.          part of the Linked List */
  509.         ptr1 = curr;
  510.         while (1 == 1) {
  511.  
  512.             /* Now start a pointer from loop_node and check if it ever
  513.              reaches ptr2 */
  514.             ptr2 = loop;
  515.             while (ptr2.next != loop && ptr2.next != ptr1) {
  516.                 ptr2 = ptr2.next;
  517.             }
  518.  
  519.             /* If ptr2 reahced ptr1 then there is a loop. So break the
  520.              loop */
  521.             if (ptr2.next == ptr1) {
  522.                 break;
  523.             }
  524.  
  525.             /* If ptr2 did't reach ptr1 then try the next node after ptr1 */
  526.             ptr1 = ptr1.next;
  527.         }
  528.  
  529.         /* After the end of loop ptr2 is the last node of the loop. So
  530.          make next of ptr2 as NULL */
  531.         ptr2.next = null;
  532.     }
  533.  
  534.     // Function to print the linked list
  535.     void printList(Node node) {
  536.         while (node != null) {
  537.             System.out.print(node.data + " ");
  538.             node = node.next;
  539.         }
  540.     }
  541.  
  542.     // Driver program to test above functions
  543.     public static void main(String[] args) {
  544.         DetectAndRemoveLoop list = new DetectAndRemoveLoop();
  545.         list.head = new Node(50);
  546.         list.head.next = new Node(20);
  547.         list.head.next.next = new Node(15);
  548.         list.head.next.next.next = new Node(4);
  549.         list.head.next.next.next.next = new Node(10);
  550.  
  551.         // Creating a loop for testing
  552.         head.next.next.next.next.next = head.next.next;
  553.         list.detectAndRemoveLoop(head);
  554.         System.out.println("Linked List after removing loop : ");
  555.         list.printList(head);
  556.     }
  557. }
  558.  
  559. class FlattenLinkedLists {
  560.     /**
  561.      * https://www.geeksforgeeks.org/flattening-a-linked-list/
  562.      * Requires a node with succ & down, generics can't offer the same
  563.      * thus a new result list must be created which wastes memory
  564.      */
  565.  
  566.     public static void deleteDuplicates(SLL<Integer> list) {
  567.         SLLNode<Integer> i = list.getFirst();
  568.         SLLNode<Integer> j;
  569.         while (i != null) {
  570.             j = i;
  571.             while (j.succ != null) {
  572.  
  573.                 if (i.element.equals(j.succ.element)) {
  574.                     j.succ = j.succ.succ;
  575.                 } else {
  576.                     j = j.succ;
  577.                 }
  578.             }
  579.             i = i.succ;
  580.         }
  581.     }
  582.  
  583.     public static void main(String args[]) {
  584.         SLL<SLL<Integer>> list = new SLL<>();
  585.         for (int i = 0; i < 5; i++) {
  586.             SLL<Integer> temp = new SLL<>();
  587.             for (int j = 0; j < 5; j++) {
  588.                 temp.insertFirst(j + 1);
  589.             }
  590.             list.insertFirst(temp);
  591.         }
  592.  
  593.         SLL<Integer> result = new SLL<>();
  594.         SLLNode<SLL<Integer>> node = list.getFirst();
  595.         while (node != null) {
  596.             SLLNode<Integer> subnode = node.element.getFirst();
  597.             while (subnode != null) {
  598.                 result.insertFirst(subnode.element.intValue());
  599.                 subnode = subnode.succ;
  600.             }
  601.             node = node.succ;
  602.         }
  603.  
  604.         deleteDuplicates(result);
  605.         System.out.println(result);
  606.     }
  607. }
  608.  
  609. class ReverseAlternateK_Nodes {
  610.  
  611.     public static void reverseBetween(SLL<Integer> list, SLLNode<Integer> start, SLLNode<Integer> end) {
  612.         SLLNode<Integer> node = start;
  613.  
  614.         while (node != end) {
  615.             SLLNode<Integer> toDelete = node;
  616.             list.insertAfter(node.element, end);
  617.             node = node.succ;
  618.             list.delete(toDelete);
  619.         }
  620.  
  621.     }
  622.  
  623.     public static void printAlternateK_Nodes(SLL<Integer> list, Integer K) {
  624.         SLLNode<Integer> node = list.getFirst();
  625.  
  626.         Boolean alternate = true;
  627.         Integer count = K;
  628.  
  629.         SLLNode<Integer> start = node;
  630.         SLLNode<Integer> end = node;
  631.         while (node != null) {
  632.  
  633.             if (count == 1) {
  634.                 end = node;
  635.                 SLLNode<Integer> nextStart = node.succ;
  636.  
  637.                 if (alternate) {
  638.                     reverseBetween(list, start, end);
  639.                 }
  640.  
  641.                 if (nextStart == null) break;
  642.  
  643.                 start = nextStart;
  644.                 node = start;
  645.  
  646.                 count = K;
  647.                 alternate = !alternate;
  648.             }
  649.  
  650.             count--;
  651.  
  652.             if (node.succ == null) {
  653.                 break;
  654.             }
  655.  
  656.             node = node.succ;
  657.         }
  658.         reverseBetween(list, start, node);
  659.     }
  660.  
  661.     public static void main(String args[]) {
  662.         SLL<Integer> list = new SLL<>();
  663.         for (int i = 0; i < 12; i++) {
  664.             list.insertLast(i + 1);
  665.         }
  666.  
  667.         SLLNode<Integer> start = list.find(1);
  668.         SLLNode<Integer> end = list.find(12);
  669.  
  670.         System.out.println(list);
  671.         reverseBetween(list, start, end);
  672.         System.out.println(list);
  673.     }
  674. }
  675.  
  676. class ReverseWordInSentence {
  677.     public static void printWords(SLL<Character> list) {
  678.         SLLNode<Character> current = list.getFirst();
  679.  
  680.         while (current != null) {
  681.  
  682.             System.out.print(current.element);
  683.  
  684.             if (current.succ == null) break;
  685.  
  686.             if (current.succ.element == ' ') {
  687.                 current = current.succ.succ;
  688.                 System.out.print("\n");
  689.             } else {
  690.                 current = current.succ;
  691.             }
  692.         }
  693.         System.out.print("\n");
  694.     }
  695.  
  696.     public static void reverseWord(SLLNode<Character> start, SLLNode<Character> end, SLL<Character> list) {
  697.         SLLNode<Character> afterEnd = end.succ;
  698.  
  699.         while (start != end.succ) {
  700.             list.insertBefore(start.element, afterEnd); // This shifts end.succ
  701.             afterEnd = end.succ; // so we update afterEnd
  702.             SLLNode<Character> toRemove = start;
  703.             start = start.succ;
  704.             list.delete(toRemove);
  705.         }
  706.     }
  707.  
  708.     public static void reverseWords(SLL<Character> list) {
  709.         SLLNode<Character> current = list.getFirst();
  710.  
  711.         SLLNode<Character> start = current;
  712.         SLLNode<Character> end;
  713.  
  714.         while (current != null) {
  715.  
  716.             if (current.succ == null) {
  717.                 end = current;
  718.                 reverseWord(start, end, list);
  719.                 break;
  720.             }
  721.  
  722.             if (current.succ.element == ' ') {
  723.                 end = current;
  724.                 SLLNode<Character> nextStart = current.succ.succ;
  725.  
  726.                 reverseWord(start, end, list);
  727.  
  728.                 start = nextStart;
  729.                 current = start;
  730.             } else {
  731.                 current = current.succ;
  732.             }
  733.         }
  734.     }
  735.  
  736.     public static void main(String[] args) {
  737.         String s = "123 45 67 890";
  738.  
  739.         SLL<Character> list = new SLL<>();
  740.         for (int i = 0; i < s.length(); i++) {
  741.             list.insertLast(s.charAt(i));
  742.         }
  743.  
  744.  
  745.         System.out.println(list);
  746.  
  747.         reverseWords(list);
  748.  
  749.         System.out.println();
  750.         System.out.printf("Original: 123 45 67 890\n");
  751.         System.out.printf("Expected: 321 54 76 098\n");
  752.         System.out.printf("Result  : %s\n", list);
  753.  
  754.  
  755.     }
  756. }
  757.  
  758. public class LinkedListFun {
  759.  
  760.     public static void main(String args[]) {
  761.         SLL<Integer> list = new SLL<>();
  762.         for (int i = 0; i < 10; i++) {
  763.             list.insertFirst(i);
  764.         }
  765.  
  766.         System.out.println(list);
  767.         list.setFirst(list.reverse(list.getFirst()));
  768.         System.out.println(list);
  769.     }
  770. }
  771.  
  772. /**
  773.  * Првата беше дадени влезови мерења на PM10 честички од тип „Центар 100“ итн и да се најде за некоја општина просечен број на честички,
  774.  * втората беше да се провери бинарно дрво дали е комплетно,
  775.  * третата беше дадено поле mxn со пречки и робот шо се движи по рабовите на полињата (зафаќа 4 полиња наеднаш и не смее да зафаќа поле со пречка) и да се најде најкраток пат од една до друга позиција 3
  776.  */
  777.  
  778.  
  779. class Node {
  780.     Integer data;
  781.     Node next;
  782.  
  783.     Node(int data) {
  784.         this.data = data;
  785.         this.next = null;
  786.     }
  787.  
  788.     Node(int data, Node next) {
  789.         this.data = data;
  790.         this.next = next;
  791.     }
  792.  
  793.     @Override
  794.     public String toString() {
  795.         return String.format("(%d)", data);
  796.     }
  797. }
  798.  
  799. class mySLL {
  800.  
  801.     public static void main(String args[]) {
  802.         mySLL one = new mySLL();
  803.         mySLL two = new mySLL();
  804.  
  805.         one.insertFirst(9);
  806.         one.insertFirst(9);
  807.         one.insertFirst(9);
  808.  
  809.         two.insertFirst(8);
  810.         two.insertFirst(1);
  811.  
  812.         mySLL ans = one.add(two);
  813.  
  814.         ans.printList();
  815.  
  816.     }
  817.  
  818.     Node first = null;
  819.  
  820.     void insertFirst(int data) {
  821.         if (first == null) {
  822.             first = new Node(data);
  823.             return;
  824.         }
  825.         Node insert = new Node(data, first);
  826.         first = insert;
  827.     }
  828.  
  829.     void insertBefore(int data, Node node) {
  830.         if (first == null) {
  831.             insertFirst(data);
  832.             return;
  833.         }
  834.  
  835.         if (node == null) {
  836.             return;
  837.         }
  838.  
  839.         if (first == node) {
  840.             insertFirst(data);
  841.             return;
  842.         }
  843.  
  844.         Node previous = first;
  845.         Node current = first.next;
  846.         while (current != node) {
  847.             previous = current;
  848.             current = current.next;
  849.         }
  850.  
  851.         Node insert = new Node(data, current);
  852.         previous.next = insert;
  853.  
  854.     }
  855.  
  856.     void insertAfter(int data, Node node) {
  857.         if (first == null) {
  858.             insertFirst(data);
  859.             return;
  860.         }
  861.  
  862.         if (node == null) {
  863.             return;
  864.         }
  865.  
  866.         Node insert = new Node(data, node.next);
  867.         node.next = insert;
  868.  
  869.     }
  870.  
  871.     int length() {
  872.         if (first == null) return 0;
  873.         Node current = first;
  874.         int length = 0;
  875.         while (current != null) {
  876.             length++;
  877.             current = current.next;
  878.         }
  879.         return length;
  880.     }
  881.  
  882.     void mergeAnotherAlternatively(mySLL that) {
  883.         Node one = first;
  884.         Node two = that.first;
  885.  
  886.         while (one != null) {
  887.  
  888.             if (one.next == null) return;
  889.  
  890.             this.insertAfter(two.data, one);
  891.  
  892.             one = one.next.next;
  893.             two = two.next;
  894.         }
  895.  
  896.     }
  897.  
  898.     int lengthOfLongestSublist(Node node) {
  899.         /**
  900.          * https://www.geeksforgeeks.org/longest-increasing-sublist-linked-list/
  901.          * */
  902.  
  903.         if (node == null) return 0;
  904.         Node current = node;
  905.         Node following = node.next;
  906.  
  907.         int maxLength = Integer.MIN_VALUE;
  908.         int length = 0;
  909.  
  910.         while (current.next != null) {
  911.  
  912.             if (current.data <= following.data) {
  913.                 length++;
  914.             } else {
  915.                 length = 0;
  916.             }
  917.  
  918.             maxLength = Math.max(maxLength, length);
  919.  
  920.             current = current.next;
  921.             following = current.next;
  922.         }
  923.  
  924.         return maxLength + 1;
  925.     }
  926.  
  927.     /**
  928.      * https://www.geeksforgeeks.org/sum-of-two-linked-lists/
  929.      */
  930.  
  931.     mySLL add(mySLL that) {
  932.         int lenOne = this.length();
  933.         int lenTwo = that.length();
  934.         int diff = 0;
  935.  
  936.         Node bigger, smaller;
  937.  
  938.         // temp1 should point to the longer linkedlist
  939.         if (lenTwo > lenOne) {
  940.             bigger = that.first;
  941.             smaller = this.first;
  942.             diff = Math.abs(lenTwo - lenOne);
  943.         } else {
  944.             smaller = that.first;
  945.             bigger = this.first;
  946.             diff = Math.abs(lenTwo - lenOne);
  947.         }
  948.  
  949.         Node first = bigger;
  950.  
  951.         // increment temp1 till temp1 and temp2 have same lengths to end of list
  952.         while (diff > 0) {
  953.             bigger = bigger.next;
  954.             diff--;
  955.         }
  956.  
  957.         mySLL answer = new mySLL();
  958.  
  959.         int carry = addRecursively(bigger, smaller, answer);
  960.  
  961.         // if any carry add that to the remaining linkedlist of temp1
  962.         if (carry != 0) {
  963.             int c = addCarry(first, bigger, answer);
  964.             if (c == 1)    // extra carry after final addition - push that as well
  965.                 answer.insertFirst(1);
  966.         }
  967.  
  968.         return answer;
  969.     }
  970.  
  971.     // add equal lengths of both linked lists recursively - returns carry
  972.     int addRecursively(Node bigger, Node smaller, mySLL answer) {
  973.         if (bigger == null && smaller == null) return 0;
  974.  
  975.         int sum = bigger.data + smaller.data + addRecursively(bigger.next, smaller.next, answer);
  976.  
  977.         answer.insertFirst(sum % 10); // push ones digit alone
  978.         return sum / 10; // return carry
  979.     }
  980.  
  981.     // add carry of addRecursively to remaining linkedlist
  982.     int addCarry(Node first, Node bigger, mySLL answer) {
  983.         if (first == bigger)
  984.             return 1;    // carry from addRecursively added
  985.  
  986.         int sum = first.data + addCarry(first.next, bigger, answer);
  987.         answer.insertFirst(sum % 10);
  988.  
  989.         return sum / 10;
  990.     }
  991.  
  992.     void printList() {
  993.         Node temp = first;
  994.         while (temp != null) {
  995.             System.out.printf("(%d)->", temp.data);
  996.             temp = temp.next;
  997.         }
  998.         System.out.println();
  999.     }
  1000.  
  1001.     @Override
  1002.     public String toString() {
  1003.         StringBuffer sb = new StringBuffer();
  1004.         Node current = first;
  1005.         while (current != null) {
  1006.             sb.append(current).append("->");
  1007.             current = current.next;
  1008.         }
  1009.         return sb.toString();
  1010.     }
  1011. }
Advertisement
Add Comment
Please, Sign In to add comment