链表逆转三种方式

    static class Node {
        int val;
        Node next;

        public Node(int val, Node next) {
            this.val = val;
            this.next = next;
        }
    }

    static Node reverse(Node head) {
        if (head.next == null) {
            return head;
        }

        Node result = reverse(head.next);
        head.next.next = head;
        head.next = null;
        return result;
    }

    static Node reverse1(Node head) {
        Node prev = null;
        Node cur = head;
        while (cur != null) {
            Node next = cur.next;
            cur.next = prev;
            prev = cur;
            cur = next;
        }
        return cur;
    }


    static Node reverse2(Node prev, Node cur) {
        if (cur == null) return prev;
        Node next = cur.next;
        cur.next = prev;
        return reverse2(cur, next);
    }

posted @ 2022-01-20 15:29  dxyoung  阅读(70)  评论(0)    收藏  举报