1. 程式人生 > >【leetCode】25_k個一組翻轉連結串列

【leetCode】25_k個一組翻轉連結串列

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        int count = 0;
        ListNode h = head, cur, Head, kHead, t;

        while (h != null){
            count ++;
            h = h.next;
        }
        int m = count / k;


        Head = new ListNode(0);
        Head.next = head;
        h = Head;
        cur = head;

        int i = 0;
        for (i = 0; i < m; i ++){
            cur = cur.next;
            for (int j = 0; j < k - 1; j ++){
                t = cur.next;
                cur.next = h.next;
                h.next = cur;
                cur = t;
            }
            for (int j = 0; j < k; j ++){
                h = h.next;
            }
            h.next = cur;

        }
        return Head.next;
    }
}