Reverse a linked list

Sort by

recency

|

54 Discussions

|

  • + 0 comments

    Java Solution:

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

    Here is HackerRank Reverse a linked list problem solution in python java c++ c and javascript

  • + 0 comments

    Scala, with recursion:

         def reverse(llist: SinglyLinkedListNode): SinglyLinkedListNode = {
          @tailrec
          def reverseNode(node: SinglyLinkedListNode, next: SinglyLinkedListNode): SinglyLinkedListNode = {
            if (node == null) next
            else {
              val prev = node.next
              node.next = next
              reverseNode(prev, node)
            }
          }
          reverseNode(llist, null)
        }
    
  • + 0 comments
    def reverse(llist):
        curr_node = llist
        head = None
        while curr_node is not None:
            pre_node = curr_node.next
            curr_node.next = head
            head = curr_node
            curr_node = pre_node
        return head
        # Example process:
        # Initial list: head = (1) -> 2 -> 3 -> None
        # Reversed list building process:
        #
        # Before Loop:             head = (None),                curr_node = 1
        # While-loop:
        # Loop-1: pre_node = 2,    head = (1) -> None,           curr_node: 1 => 2
        # Loop-2: pre_node = 3,    head = (2) -> 1 -> None,      curr_node: 2 => 3
        # Loop-3: pre_node = None, head = (3) -> 2 -> 1 -> None, curr_node: 3 => None
        #
        # Reversed list: head = (3) -> 2 -> 1 -> None
    
  • + 0 comments
    // A -> B -> C -> D -> E
    
    // A -> NULL
    // B -> A
    // C -> B
    // D -> C
    // E -> D
    
    function reverse($llist) {
        $prev = NULL;
        while($llist) {
            $old_next = $llist->next;
            $llist->next = $prev;
            $prev = $llist;
            $llist = $old_next;
        }
        return $prev;
    }