Iterative and recursive java solutions


  • 0
    B
    public ListNode reverseList(ListNode head) {
        ListNode pre = null;
        while (head != null) {
            ListNode tmp = head.next;
            head.next = pre;
            pre = head;
            head = tmp;
        }
        return pre;
    }
    
    
    private ListNode newHead;
    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) {
            newHead = head;
            return head;
        }
    
        ListNode tail = reverseList(head.next);
        tail.next = head;
        head.next = null;
        return head;
    }

  • 0
    H
    This post is deleted!

Log in to reply
 

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