牛客网BM2 链表内指定区间反转

思路:

  1. 首先先定位需要反转的链表前的节点,和定位链表长度的前节点。
  2. 把定位到的节点进行分隔
  3. 分隔出来的节点就是需要反转的链表
  4. 把链表进行反转
  5. 然后拼接回去
    
    
    import java.util.List;
    
    /**
     * @author xienl
     * @description 链表内指定区间反转
     * @date 2022/6/6
     */
    
    public class Solution {
        public static void main(String[] args) {
            Solution solution = new Solution();
            ListNode listNode = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5)))));
            listNode = solution.reverseBetween(listNode, 2, 4);
            listNode.print();
        }
    
        public ListNode reverseBetween (ListNode head, int m, int n) {
            ListNode dummy = new ListNode();
            dummy.val = -1;
            dummy.next = head;
            ListNode cur = dummy;
            // 获取反转之前的节点
            for (int i = 0; i < m - 1; i++){
                cur = cur.next;
            }
    
            // 反转之后的节点
            ListNode tail = cur.next;
            for (int i = 0; i < n - m ; i++){
                tail = tail.next;
            }
            ListNode next = tail.next;
            tail.next = null;
            // 分隔的头节点变成了需要拼接的下一个节点的节点
            tail = cur.next;
    
            // 需要反转的节点
            ListNode transform = revise(cur.next);
    
    
            // 反转之后拼接结果
            cur.next = transform;
            tail.next = next;
            return dummy.next;
        }
    
        /**
         * 反转链表
         * @param node
         * @return
         */
        private ListNode revise(ListNode node){
            // 创建一个临时的节点,用来返回
            ListNode pre = null;
            while (node != null){
                ListNode next = node.next;
                node.next = pre;
                pre = node;
                node = next;
            }
            return pre;
        }
    }
    
    class ListNode {
       int val;
       ListNode next = null;
    
       public ListNode(){};
    
       public ListNode(int val){
           this.val = val;
       }
    
        public ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    
        public void print(){
            System.out.print(this.val + " ");
            if (this.next != null){
                this.next.print();
            }
        }
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值