Recursive (31ms) and iterative (4ms) java solution


  • -3
    H
         //Iterative    
         public ListNode reverseList(ListNode head) {
                if(head == null){
                    return null;
                }
                if(head.next == null){
                    return head;
                }
                Stack<ListNode> theStack = new Stack<ListNode>();
                ListNode currentNode = head;
                ListNode newHead;
                while(currentNode!=null){
                    theStack.push(currentNode);
                    currentNode = currentNode.next;
                }
                ListNode resultHead = theStack.pop();
                ListNode returnHead = resultHead;
                while(!theStack.isEmpty()){
                    resultHead.next = theStack.pop();
                    resultHead = resultHead.next;
                }
                resultHead.next= null;
                return returnHead;
            }
            
            //recursive
            public ListNode reverseList(ListNode head) {
                if(head == null){
                    return null;
                }
                if(head.next == null){
                    return head;
                }else{
                    ListNode tempNode = reverseList(head.next);
                    ListNode currentNode = tempNode;
                    while(currentNode.next!=null){
                        currentNode = currentNode.next;
                    }
                    currentNode.next = head;
                    head.next = null;
                    return tempNode;
                }
            }

Log in to reply
 

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