Java solution using stack.


  • 0
    M

    Just adding different type of solution. Add to stack, then remove the items in the reverse order. Uses O(n) space.

    public class Solution {
            public ListNode reverseList(ListNode head) {
            if(head == null) {
                return null;
            }
            Stack<ListNode> nodes = new Stack<>();
            ListNode toAdd = head;
            while(toAdd != null) {
                nodes.push(toAdd);
                toAdd = toAdd.next;
            }
            head = nodes.pop();
            ListNode next = head;
            while(!nodes.isEmpty()) {
                ListNode p = nodes.pop();
                next.next = p;
                next = p;
            }
            next.next = null;
            return head;
        }
    }

Log in to reply
 

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