Problem: Reverse Linked List

Posted by Marcy on February 18, 2015

Question

Reverse a singly linked list.

Solution

TODO

Code

class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null) return null;
        if(head.next == null) return head;

        ListNode next = head.next;
        ListNode newHead = reverseList(next);
        next.next = head;
        head.next = null;

        return newHead;
    }
}

Performance

TODO

Solution

TODO

Code

class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null) return null;
        if(head.next == null) return head;

        ListNode newHead = null;
        while(head != null) {
            ListNode temp = newHead;
            newHead = head;
            head = head.next;
            newHead.next = temp;
        }

        return newHead;
    }
}

Performance

TODO