链表反转

  • 循环反转链表
    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;
    }

你可能感兴趣的:(链表反转)