Reverse grouping list

Question: reverse a linked list in each of the K nodes, if the length of the list can not be divisible by K, the last remainder nodes remains unchanged.

Ideas: packet for each packet permutation list. The key design transpose function, elements of the group iterative inversion.

java code:

ListNode reverseKGroup(ListNode head,int k){
        if(head==null||k<=1)
            return head;
        ListNode dummy=new ListNode(0);
        dummy.next=head;
        ListNode pre=dummy,cross=head;
        int count=0;
        while(cross!=null){
            count++;
            if(count%k==0){
                pre=reverse(pre,cross.next);
                cross=pre.next;
            }
            else{
                cross=cross.next;
            }
        }
        return dummy.next;
    }
    ListNode reverse(ListNode pre,ListNode next){
        ListNode last=pre.next;
        ListNode cur=last.next;
        while(cur!=next){
            last.next=cur.next;
            cur.next=pre.next;
            pre.next=cur;
            cur=last.next;
        }
        return last;
    }
Published 18 original articles · won praise 0 · Views 663

Guess you like

Origin blog.csdn.net/qq_42060170/article/details/104301389