Reverse Nodes in k-Group

折腾出来比较费劲,但是巩固了linked list reverse的概念

如果有 pre -> 1 -> 2 -> 3 -> 4 -> end

返回的reverse是 原来的pre.next 也就是最后reversed 了以后的list: pre -> 4 -> 3 -> 2 -> 1 -> end的那个1,在这里,reverse的function见

Reverse Linked List II, 想法是不断把cur的node B插到pre后面,再把紧靠在B前面的A链接到B的下一位去

public class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        if(head==null|| head.next==null || k<2) return head;
        ListNode h = new ListNode(-1);
        h.next = head;
        ListNode pre = h, cur = head;
        int cnt = 0;
        
        while(cur!=null){
            ListNode end = cur.next;  //以cur 为中心往后看
            cnt++;
            if(cnt==k){ 
                pre =reverse(pre, end);
                cnt = 0;
                }
            cur = end;
        }
        
        return h.next;
    }
    
    public ListNode reverse(ListNode pre, ListNode end){ // B keep to being inserted after pre  pre-1-2-3-end, 1= A, 2=B, 3=t
        ListNode A = pre.next, B  = A.next; // A 定义为B前面一位, 不断的把B塞到pre后面(也就是list的第一位,然后把原来B的前面A链接到B的后面t上去
        ListNode hd=pre.next;
        while( B!=end){
            ListNode t =  B.next;
            B.next = pre.next;
            pre.next = B;
            A.next = t;
            B=t;
        }
        return hd;
    }
}

 

posted @ 2015-04-07 11:01  世界到处都是小星星  阅读(171)  评论(0编辑  收藏  举报