等待加载。。。

算法:反转链表 java

方法1 迭代

    public static Node reverseNode(Node head){
        // 前一个节点
        Node pre = null;
        // 当前节点
        Node cur = head;
        // 如果当前节点不为空
        while(cur!=null){
            // 存储下一个节点
            Node next = cur.next;
            // 当前节点的下一个节点指向前一个节点
            cur.next = pre;
            // 前一个节点变成当前节点
            pre = cur;
            // 当前节点变成下一个节点
            cur = next;
        }
        return  pre;
    }

方法2 递归

    public static Node reverseNode(Node head){
        if(head == null || head.next == null){
            return head;
        }
        // 递归,保证每个节点都逆序
        Node node = reverseNode2(head.next);
        // 当前节点的下一个节点的下一个节点,指向当前节点,实现逆序
        head.next.next = head;
        // 下一个节点置空
        head.next = null;
        return  node;
    }
posted @ 2022-04-18 19:19  言小溪enncy  阅读(55)  评论(0编辑  收藏  举报