My Java Solution


  • 0

    Not fast but easier to understand...

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode reverseList(ListNode head) {
            if(head==null){
                return null;
            }
            ArrayDeque<ListNode> stack = new ArrayDeque<>();
            ListNode p1,start =new ListNode(0);
            while(head!=null){
                stack.push(head);
                head = head.next;
            }
            p1 = stack.pop();
            start.next = p1;
            ListNode p2;
            while(!stack.isEmpty()){
                p2 = stack.pop();
                p1.next = p2;
                p1 = p2;
            }
            p1.next = null;
            return start.next;
        }
    }
    

Log in to reply
 

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