链表反转(全链表反转、链表区间反转)

本文深入探讨了链表数据结构的两种反转方法:迭代法和递归法,并提供了详细的代码实现。同时,还介绍了如何在指定区间内进行链表反转,为读者提供了全面的链表操作指南。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 全链表反转
/**
 * Reverse a linkedList iteratively, for example
 * 1 -> 3 -> 5 -> 7 -> 9
 * 9 -> 7 -> 5 -> 3 -> 1
 * @param head
 * @return
 */
public static ListNode reverseIteratively(ListNode head) {
    ListNode prev = null;
    while(head != null) {
        ListNode next = head.next;
        head.next = prev;
        prev = head;
        head = next;
    }
    return prev;
}

/**
 * Reverse a linkedList recursively, for example
 * 1 -> 3 -> 5 -> 7 -> 9
 * 9 -> 7 -> 5 -> 3 -> 1
 * @param head
 * @return
 */
public static ListNode reverseRecursively(ListNode head) {
    if(head == null || head.next == null) {
        return head;
    }else {
        ListNode newHead = reverseRecursively(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }
}
2. 链表区间反转
/**
 * Reverse a linkedList in a given interval, for example
 * 1 -> 3 -> 5 -> 7 -> 9
 * ↑                   ↑
 * 1 -> 7 -> 5 -> 3 -> 9
 * @param nodeLeft
 * @param nodeRight
 */
public static void intervalReverse(ListNode nodeLeft, ListNode nodeRight) {
    if(nodeLeft == nodeRight) {
        return;
    }else{
        ListNode last = nodeLeft.next;
        ListNode cur = last.next;
        while(cur != nodeRight) {
            last.next = cur.next;
            cur.next = nodeLeft.next;
            nodeLeft.next = cur;
            cur = last.next;
        }
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值