天题之reverse list

最后那个reverse函数写的比较费劲,主要是pre.next 和last.next必须指向正确位置

ref 解释 http://www.cnblogs.com/lichen782/p/leetcode_Reverse_Nodes_in_kGroup.html

ref 代码 http://www.cnblogs.com/springfor/p/3864530.html

public class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        if(head==null || k<2) return head;
        ListNode dum = new ListNode(-1);
        dum.next = head;
        ListNode pre = dum, cur = head;
        int cnt=0;
        
        while(cur!=null){
            cnt++;
            ListNode next = cur.next;
            if(cnt==k){  
                pre = reverse(pre, next);
                cnt=0; 
            }
            cur = next;
            
        }
        return dum.next;
    }
    
    public   ListNode reverse(ListNode pre, ListNode next){ //pre  1->2->3 next   to  1<-2<-3, return 1
        ListNode last =  pre.next ;
        ListNode cur = last.next;
        while(cur!=next){
          <strong><span style="color:#ff0000;background-color: rgb(255, 255, 204);">  // ListNode tmp = cur.next; 这里是错误的关键,必须要把last指向正确的下一个位置
          last.next = cur.next;
            cur.next = pre.next;
            pre.next = cur;
            // cur = tmp;
          cur =  last.next;</span></strong>
        }
        return last;
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值