Search This Blog

Thursday, June 23, 2011

Reverse a singly linked list

I was asked this question during an interview today.  I didn't do well though.  I guess because it was an interview, I had some pressure and could think fast and clearly.  In fact, this question is pretty easy with the recursive.  When I got home, it didn't take me too long to figure out the correct answer.  Here is the code in Java.

class Node {
    Node next;
}

class Util {
    public static void reverseNode(Node node) {
        reverseNode(node, null);
    }
   
    private static void reverseNode(Node node, Node previous) {
        if (node != null) {
            reverseNode(node.next, node);
            node.next = previous;
        }
    }
}

Update:

The recursive solution is easy to understand and implement.  However, you may get a StackOverflow exception if the list is big.  Here is the non-recursive solution:

class Util {
    public static void reverseNode(Node node) {
        Node previous = null;
        while (node != null) {
            Node next = node.next;
            node.next = previous;
            previous = node;
            node = next;
        }
    }
}

No comments:

Post a Comment