Java翻转链表(递归和迭代两种方式)

LeetCode

递归

    public ListNode reverseList(ListNode head) {
    
    
        if (head == null || head.next == null)
            return head;
        ListNode temp = head.next;
        ListNode newHead = reverseList(head.next);
        temp.next = head;
        head.next = null;
        return newHead;
    }

迭代

    public static ListNode reverseListIterative(ListNode head) {
    
    
        ListNode prev = null; //前指针节点
        ListNode curr = head; //当前指针节点
        ListNode temp;
        //每次循环,都将当前节点指向它前面的节点,然后当前节点和前节点后移
        while (curr != null) {
    
    
            temp = curr.next; //临时节点,暂存当前节点的下一节点,用于后移
            curr.next = prev; //将当前节点指向它前面的节点
            prev = curr; //前指针后移
            curr = temp; //当前指针后移
        }
        return prev;
    }

参考资料

猜你喜欢

转载自blog.csdn.net/yu540135101/article/details/112801543