水下功夫做透,水上才能顺风顺水。

局部反转链表

给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。

    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;
       }
       int diff = right - left;
       ListNode cur = pre.next;

       for(int i=0;i<diff;i++){
          ListNode tmp = cur.next;
          cur.next = tmp.next;//重点
          tmp.next = pre.next;//重点
          pre.next = tmp;
       }
       return dummyNode.next;
    }

  

posted @ 2022-10-24 13:20  北方寒士  阅读(27)  评论(0编辑  收藏  举报