【链表】- 反转链表

1. 对应力扣题目连接

2. 实现案例代码

下面使用两种方式实现:

  • 迭代方法-反转链表
  • 递归方法-反转链表
public class ReverseLinkedList {
    public static void main(String[] args) {


        // 示例链表:[1, 2, 3, 4, 5]
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);

        // 反转链表
        ListNode reverse = reverse(null, head);

        printList(reverse); // 输出:[5, 4, 3, 2, 1]
    }

    public static void printList(ListNode head) {
        ListNode current = head;
        while (current != null) {
            System.out.print(current.val + " ");
            current = current.next;
        }
        System.out.println();
    }


    /**
     * 迭代方法反转链表
     * @param head
     * @return
     */
    public ListNode reverseListIterative(ListNode head) {
        ListNode prev = null;
        ListNode current = head;

        while (current != null) {
            ListNode next = current.next; // 保存下一个节点
            current.next = prev; // 反转当前节点的指针
            prev = current; // 移动前指针到当前节点
            current = next; // 移动当前节点到下一个节点
        }

        return prev; // 新的头节点
    }

    /**
     * 递归方法反转链表-1
     * @param head
     * @return
     */
    public ListNode reverseListRecursive(ListNode head) {
        if (head == null || head.next == null) {
            return head; // 基本情况:空链表或只有一个节点的链表
        }

        ListNode newHead = reverseListRecursive(head.next); // 反转后续链表
        head.next.next = head; // 将后续节点指向当前节点
        head.next = null; // 当前节点的next置为null

        return newHead; // 返回新的头节点
    }

    /**
     * 递归方法反转链表-2
     * @param prev
     * @param cur
     * @return
     */
    private static ListNode reverse(ListNode prev, ListNode cur) {
        if (cur == null) {
            return prev;
        }
        ListNode temp = cur.next;// 先保存下一个节点
        cur.next = prev;// 反转
        // 更新prev、cur位置
        // prev = cur;
        // cur = temp;
        return reverse(cur, temp);
    }
}

/**
 * 节点类
 */
class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}

  • 12
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值