算法通关村第二关——链表指定区间反转问题解析

LeetCode92 反转链表II
 

下面介绍三种方法

1.头插法

image.png

 

image.png

 所谓头插法,就是再反转区间里,每次向后遍历一个结点,就将它插入到,反转区间的头部。

class Solution {
    public ListNode reverseBetween(ListNode head, int left, int right) {
        ListNode dummyNode = new ListNode(-1);
        dummyNode.next = head;
        ListNode pre = dummyNode;
        for(int i = 0;i < left - 1;i++)
            pre = pre.next;
        ListNode cur = pre.next;
        ListNode tmp;
        for(int i = 0;i < right - left;i++){
            tmp = cur.next;
            cur.next = tmp.next;
            tmp.next = pre.next;
            pre.next = tmp;
        }
        return dummyNode.next;
    }
}
2.穿针引线法

image.png

所谓穿针引线法就是先记录反转区间的头、尾结点和他们前后的结点。

然后反转这个区间后,再将他连接上。

class Solution {
    public ListNode reverseBetween(ListNode head, int left, int right) {
        ListNode dummyNode = new ListNode(-1);
        dummyNode.next = head;
        ListNode pre = dummyNode;
        for(int i = 0;i < left - 1;i++)
            pre = pre.next;
        ListNode rNode = pre;
        ListNode lNode = pre.next;
        for(int i = 0;i < right - left + 1;i++)
            rNode = rNode.next;
        ListNode suc = rNode.next;
        pre.next = null;
        rNode.next = null;
        reverseListNode(lNode);
        pre.next = rNode;
        lNode.next = suc;

        return dummyNode.next;
    }

    ListNode reverseListNode(ListNode head){
        ListNode pre = null;
        ListNode tmp = null;
        ListNode cur = head;
        while(cur != null){
            tmp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = tmp;
        }
        return pre;
    }
}
 3.递归
class Solution {
    //用于记录边界结点
    public ListNode reverseBetween(ListNode head, int left, int right) {
        // 递归边界
        if (left==1)
            return revserList(head,right);
        head.next = reverseBetween(head.next, left - 1, right - 1); 
        return head;
    }
    //反转链表的前n个结点
    //递归解法
    public ListNode revserList(ListNode head ,int n){
        //记录尾结点位置,避免链表断开
        ListNode tail ;
        //递归边界
        if(n==1)
            return head ;
        ListNode last=revserList(head.next,n-1);
        tail=head.next.next;
        head.next.next=head;
        head.next=tail;
        return last;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值