underwindfall / Algorithme

练习总结算法的地方
https://qifanyang.com/resume
1 stars 0 forks source link

LCOF24 #360

Closed underwindfall closed 2 years ago

underwindfall commented 2 years ago
 // time O(n)
    // space O(1)
    class Recursive {
        public ListNode reverseList(ListNode head) {
            if (head == null || head.next == null) {
                return head;
            }
            ListNode next = reverseList(head.next);
            head.next.next = head;
            head.next = null;
            return next;
        }
    }

    //time O(n)
    //space O(1)
    class DummyNode {
        public ListNode reverseList(ListNode head) {
            ListNode dummy = new ListNode(-1);
            while (head.next != null) {
                ListNode next = head.next;
                head.next = dummy.next;
                dummy.next = head;
                head = next;
            }
            return dummy.next;
        }
    }