每隔K步反转链表

每隔6步反转链表

0->1->2->3->4->5->6->7->8->9
5->4->3->2->1->0->6->7->8->9

每隔3步反转链表

0->1->2->3->4->5->6->7->8->9
2->1->0->5->4->3->8->7->6->9

public class ListNode {
    int val;
    ListNode next;

    public ListNode (int val){
        this.val =val;
    }

    @Override
    public String toString() {
        if (this.next == null) {
            return String.valueOf(this.val);
        }
        return this.val + "->" + this.next.toString();
    }

}

 class Reverse {

     public static ListNode reverseKGroup(ListNode head, int k) {
         ListNode dummy = new ListNode(0);
         dummy.next = head;

         ListNode pre = dummy;
         ListNode end = dummy;

         while (end.next != null) {
             for (int i = 0; i < k && end != null; i++) end = end.next;
             if (end == null) break;
             ListNode start = pre.next;
             ListNode next = end.next;
             end.next = null;
             pre.next = reverse(start);
             start.next = next;
             pre = start;

             end = pre;
         }
         return dummy.next;
     }

     private static ListNode reverse(ListNode head) {
         ListNode pre = null;
         ListNode curr = head;
         while (curr != null) {
             ListNode next = curr.next;
             curr.next = pre;
             pre = curr;
             curr = next;
         }
         return pre;
     }



    public static void main(String[] args) {
        ListNode node = createTestLinkedList();

        System.out.println(node);

        System.out.println(reverseKGroup(node, 6));

    }

    private static ListNode createTestLinkedList() {
        ListNode head = new ListNode(0);
        ListNode curNode = head;
        for (int i = 1; i < 10; i++) {
            curNode.next = new ListNode(i);
            curNode = curNode.next;
        }
        return head;
    }
}

 

你可能感兴趣的:(算法)