算法:反转链表 java

2023-11-11

方法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;
    }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

算法:反转链表 java 的相关文章

随机推荐