Iteratively and recursively Java Solution


  • 15
    S
    public class Solution {
        public ListNode reverseList(ListNode head) {
        	if(head == null) return head;
        	
        	ListNode next = head.next;
        	head.next = null;
            
        	while(next != null){
            	ListNode temp = next.next;
            	next.next = head;
            	head = next;
            	next = temp;
            }
        	return head;
        }
    }
    
    
    public class Solution {
        public ListNode reverseList(ListNode head) {
        	if(head == null) return head;
        	ListNode next = head.next;
        	head.next = null;
        	
        	return recursive(head,next);
        }
        
        private ListNode recursive(ListNode head, ListNode next){
        	if(next == null)	return head;
        	ListNode temp = next.next;
        	next.next = head;
        	return recursive(next,temp);
        	
        }
    }

Log in to reply
 

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