Java 308ms using a stack


  • 1
    public class Solution {
    	public ListNode reverseList(ListNode head) {
    		if(head == null) return head;
    		Stack<ListNode> stack = new Stack<ListNode>();
    		ListNode p = head;
    		while(p != null) {
    			stack.push(p);
    			p = p.next;
    		}
    		ListNode root = stack.peek();
    		while(!stack.isEmpty()){
    			ListNode first = stack.pop();
    			if(!stack.isEmpty()) first.next = stack.peek();
    			else first.next = null;
    		}
    		return root;
        }
    }

Log in to reply
 

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