剑指 Offer 24. 反转链表

链表k个一组翻转中,对第二部中,翻转k个节点进行优化。和直接反转链表还是有明显区别的。主要是while条件的设置。

翻转链表

    public ListNode reverseList(ListNode head) {
        ListNode  l3 = null;
        while(head!=null){
            ListNode temp = head.next;
            head.next =l3;
            l3= head;
            head=temp;
        }
        return l3;
    }

 

翻转k个结点

    public static  ListNode reverseKGroup(ListNode head, int k) {
        if(head == null)
            return null;
        ListNode temp = new ListNode(0);
        temp.next = head;
        ListNode pre = temp;
        ListNode nhead = pre.next;
        while(nhead!=null) {
            ListNode tail = pre;
            for (int i = 0; i < k; i++) {
                tail = tail.next;
                if (tail == null)
                    return temp.next;
            }
            ListNode nex = tail.next;
            ListNode[] reversehead = swapPairs(nhead, tail,k);
            ListNode newhead = reversehead[0];
            ListNode newtail = reversehead[1];
            pre.next = newhead;
            newtail.next = nex;
            pre = newtail;
            nhead = pre.next;
        }
        return temp.next;
    }
    public static  ListNode[] swapPairs(ListNode head,ListNode tail,int k) {
     /*  
     写法一:
      ListNode l3=null;
        for(int i=0;i<k;i++){//不要用while(haed!=null),比如12345,3,其对12345倒叙了
          ListNode temp = head.next;
          head.next = l3;
          l3 = head;
          head = temp;
       }  
    //找到尾指针
        ListNode newtail =l3;
        while(k!=1) {
            newtail = newtail.next;
            k--;
        }
       return new ListNode[]{l3, newtail};
        /*   

/*写法二
             ListNode prev = tail.next;
             ListNode p = head;
             while (prev != tail) {
                 ListNode nex = p.next;
                 p.next = prev;
                 prev = p;
                 p = nex;
             }
             return new ListNode[]{tail, head};

         */
        /*
        写法三:优化写法一
        不直接操作head 直接返回 tail head 不用和写法一一样去找尾指针了
         */
        ListNode l3=tail.next;
        ListNode p=head;
       // for(int i=0;i<k;i++){
        while(l3!=tail){//和for循环等价
          ListNode temp = p.next;
            p.next = l3;
          l3 = p;
            p = temp;
       }
//        ListNode newtail =l3;
//        while(k!=1) {
//            newtail = newtail.next;
//            k--;
//        }
       return new ListNode[]{tail, head};

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值