有关反转链表模板(汇总)

有关反转链表模板

反转整个链表(迭代与递归实现)

// 迭代实现
 ListNode reverse(ListNode head) {
        ListNode pre = null, cur = head, next;
        while (cur != null) {
            next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
    // 递归实现 n为链表节点数实现整个链表反转,n还可以为小于链表节点总数的值,则反转一段链表
    // 从后往前反转,首先直接递归定位到链表最后一个节点
    public ListNode reverseList(ListNode head, int n) {
        if (n == 1) {
            lastNode = head.next;
            return head;
        }
        ListNode last = reverseList(head.next, n - 1);
        head.next.next = head;
        head.next = lastNode;
        return last;
    }
    ```

## 反转链表(head开头)第1到n个节点范围的链表反转
```java
 // 反转链表第1到n个节点范围的链表
    ListNode lastNode = null;
    public ListNode reverse(ListNode head, int n) {
        if(n == 1) {
            lastNode = head.next;
            return head;
        }
        ListNode last = reverse(head.next, n - 1);
        head.next.next = head;
        head.next = lastNode;
        return last;
    }
    ```

## 反转head第m个位置开始的节点起数第n-m个节点内范围的链表
```java
 public ListNode reverse(ListNode head, int m, int n) {
        if(m == 1) { // 反转head第m个位置开始的节点起数第n-m个节点内范围的链表
            return reverse(head, n);
        }
        // 一定要有head.next = reverse(),因为下面return要返回当前操作完成的一个完整链
        head.next = reverse(head.next, m - 1, n - 1);
        return head;
    }
    ```
## 从前往后反转, 反转以a开始并以b结尾的链表(反转时不包括节点b)
```java
// 从前往后反转, 反转以a开始并以b结尾的链表(反转时不包括节点b)
    public ListNode reverseList(ListNode a, ListNode b) {
        ListNode pre = null, cur = a, next;
        while (cur != b) { // pre,cur,next指针整体向后平移
            next = cur.next; // 保存下一个指针
            cur.next = pre;// 反转
            pre = cur; // 平移
            cur = next;
        }      

        return pre; // 返回cur的前一个节点pre
    }
    ```
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值