Reverse a linked list

Sort by

recency

|

32 Discussions

|

  • + 0 comments

    js

    function reverse(llist) {
      let prev = null
      let current = llist
      let next = null
      
      while(current !== null) {
          next = current.next
          current.next = prev
          prev = current
          current = next
      }
    llist = prev
    return llist
    }
    
  • + 0 comments

    Things that I like about this: 'while llist' is quite a nice and expressive way of continuing until you hit the terminal None. Returning 'previous_node', defaulted to None, handles the case of an empty llist (single value: None) 'correctly' for the definition.

    Things I'm not convinced about: Python should let you swap three variables inline without needing a temporary variable (a, b, c = c, a, b) but expressing things like this feels harder to read (and order is important) versus having a temporary variable and doing things on separate lines.

    def reverse(llist):    
        previous_node = None
        while (llist):
            # store next (forward) node link in a temporary name
            next_node = llist.next
            # update node and re-point 'next' backwards
            llist.next = previous_node
            # update the previous node pointer for the next loop
            previous_node = llist
            # advance the 'head' pointer to continue
            llist = next_node
        return previous_node
    
  • + 0 comments

    For the Haskell version:

    Who in their damn mind had the great idea of causing a name clash with the reverse function at Data.List and making it impossible to fix the template code?? It does not even compile because of a mistake in the grayed out code.

  • + 0 comments

    Java 15

     public static SinglyLinkedListNode reverse(SinglyLinkedListNode llist) {
            SinglyLinkedListNode prev = null;
            SinglyLinkedListNode current = llist;
            SinglyLinkedListNode nextNode = null;
    
            while (current != null) {
                nextNode = current.next;
                current.next = prev;
                prev = current;
                current = nextNode;
            }
            return prev;
        }
    
  • + 0 comments

    Kotlin version has a bug. It will not add a space between testcases. So it will fail because of that. Also Java 8 version won't compile beacause of static declaration. Waste of time.