My Hive Posts

    Solution of Coding challenge #2 by @armandocat

    I have participated in (Coding challenge #2)(https://steemit.com/contest/@armandocat/coding-challenge-2-win-sbd-if-you-solve-the-problem) organized by @armandocat and here is my solution.

    The Coding Challenge Was

    In a Linked list, each node has a value and a next node. Given a Linked list:

    Write a function that reverse the linked list, using a recursive algorithm. Write a function that reverse the linked list, using a iterative algorithm. For instance: given A -> B -> C it returns C -> B ->A You don't have to clone the nodes, you must just work on their next properties.

    Since the Preferred Language was JavaScript, I have written in that. There is a starting code which you can get it from here https://pastebin.com/tHBtHZVF.

    The solution for Iterative Reversal of Linked List. Iterative Reversal means you can reverse each element one by one by using a loop. I have used while loop.

    function reverseIterative(obj) {
      // Keeping the copy of obj locally and making original object as null
      var node = obj;
      obj = null;
    
      // Starting the while loop
      while(node) {
       // In Javascript you can get the next element in the linked list using .next
       // So keeping the next element as a local copy
        var nextNode = node.next;
       // In the next three lines we are just swapping the elements from Previous to Next
        node.next = obj;
        obj = node;
        node = nextNode;
      }
      // Once we get our object, send the object back
      return obj;
    }
    

    The solution for Recursive Reversal of Linked List. Recursive meaning that the function will call itself.

    function reverseRecursive(obj) {
      // We will check if the obj or obj.next is null or undefined, if it is just return it
      if (!obj || !obj.next) {
        return obj;
      }
     // Keeping a local copy of obj
      var nextNode = obj.next;
      // Calling the Recursive Function using the next node (Recursion)
      var currentNode = reverseRecursive(nextNode);
      //Now the resursion function will be called until the obj is not null.
      obj.next = null;
      nextNode.next = obj;
      // For each funtion call we will return the currentNode
      return currentNode;
    }
    

    The output is shown below :

    You can get the full solution here: https://repl.it/LWfO/0. A lot of improvements can be made, like removing the unnecessary local variable. Any suggestion is welcomed.


    Follow @codingdefined