A non-mutative solution in JS

  • 0

    Here's my solution in JavaScript that doesn't mutate the original list:

    var reverseList = function(head) {
        var tail = null;
        if (head) {
            tail = new ListNode(head.val);
            head = head.next;
            tail.next = null;
            while (head) {
                var next = head.next;
                var temp = new ListNode(head.val);
                temp.next = tail;
                tail = temp;
                head = next;
        return tail;

    Anyone let me know if you have any suggestions!

  • 0

    You are swapping values, what can be really expensive. Just imagine that every value can be file with 100Mb of weight.

  • 0

    well yeah, but the idea was to make it non-mutative. I could have done it more easily (and initially did) if mutation wasn't a concern. Do you have a means of immutatively doing it without the overhead?

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.