链表反转

  • 循环反转链表
    private static ListNode reverse(ListNode head) {
        ListNode next = null;
        ListNode previous = null;
        ListNode newHead = null;
        ListNode current = head;
        while (current != null) {
            next = current.next;
            if (next == null) {
                newHead = current;
            }
            current.next = previous;
            previous = current;
            current = next;
        }
        return newHead;
    }
  • 递归反转链表
    public static ListNode reverseByRecursion(ListNode head) {

        if (head == null || head.next == null)
            return head;
        ListNode prev = reverseByRecursion(head.next);// 把头节点之后的节点反转后,再把头节点反转即可
        head.next.next = head;
        head.next = null;
        return prev;
    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容