1. 程式人生 > >25. Reverse Nodes in k-Group

25. Reverse Nodes in k-Group

art nbsp toc count tno current have ren ini

第二輪最後interviewer 直接說you are done for today
1st round:-google 1point3acres
you have 2 available operations, /3 and *2, given an integer n, what is the minimum steps to get n from 1 using those 2 ops.
2nd round:
stock prices
The interviewer in 2nd round said and I quote "many interviewers dropped out so they found me sorry keep you waiting"

pre 和end 的位置

class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        
        ListNode h = head;
        int len = 0;
        while (h != null) {
            len++;
            h = h.next;
        }
        if (len < 2 || k == 1 || len < k) {
            return head;
        }
        
        int m = len / k;
        ListNode end = null;
        ListNode newHead = null;
        ListNode pre = null;
        while (m > 0) {
            int cnt = k;
            ListNode tail = null;
            end = head;
            while (cnt > 0) {
                ListNode temp = head.next;
                head.next = tail;
                tail = head;
                head = temp;
                cnt--;
            }
            if (m == len / k) {
                newHead = tail;
            } else {
                pre.next = tail;
            }
            pre = end;
            m--;
        }
        end.next = head;
        return newHead;
    }
}

  

recursion

    public ListNode reverseKGroup(ListNode head, int k) {
    ListNode curr = head;
    int count = 0;
    while (curr != null && count != k) { // find the k+1 node
        curr = curr.next;
        count++;
    }
    if (count == k) { // if k+1 node is found
        curr = reverseKGroup(curr, k); // reverse list with k+1 node as head
        // head - head-pointer to direct part, 
        // curr - head-pointer to reversed part;
        while (count-- > 0) { // reverse current k-group: 
            ListNode tmp = head.next; // tmp - next head in direct part
            head.next = curr; // preappending "direct" head to the reversed list 
            curr = head; // move head of reversed part to a new node
            head = tmp; // move "direct" head to the next node in direct part
        }
        head = curr;
    }
    return head;
}

  

25. Reverse Nodes in k-Group