Iterative method based on stack. Java solution


  • 0
    O
    public class Solution {
        public ListNode reverseList(ListNode head) { 	
        	if (head == null || head.next == null) {
        		return head;
        	}
        	
        	ListNode it = head, node = null;
        	Stack<ListNode> stack = new Stack<ListNode>();
        	while(it != null) {
        		stack.push(it);
        		it = it.next;
        	}
        	it = stack.pop();
        	while(!stack.isEmpty()) {
        		node = stack.pop();
        		node.next.next = node;
        		node.next = null;
        	}
        	
            return it;
        }
    }

  • 0
    W

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

    	ListNode it = head;
    	ListNode node = null;
    	
    	Stack<ListNode> stack = new Stack<ListNode>();
    	while(it != null){
    		stack.push(it);
    		it = it.next;
    	}
    
    	it = stack.pop();
    	ListNode p = it;
    	
    	while(!stack.isEmpty()){
    		node = stack.pop();
    		node.next = p.next;
    		p.next = node;
    		p = p.next;
    	}
    
    	return it;
    }
    

    }


Log in to reply
 

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